File: mask.c

package info (click to toggle)
pygame 2.6.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 43,076 kB
  • sloc: ansic: 66,932; python: 48,797; javascript: 1,153; objc: 224; sh: 121; makefile: 59; cpp: 25
file content (2653 lines) | stat: -rw-r--r-- 81,132 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
/*
  Copyright (C) 2002-2007 Ulf Ekstrom except for the bitcount function.
  This wrapper code was originally written by Danny van Bruggen(?) for
  the SCAM library, it was then converted by Ulf Ekstrom to wrap the
  bitmask library, a spinoff from SCAM.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

/* a couple of print debugging helpers */
/*
#define CALLLOG2(x,y) fprintf(stderr, (x), (y));
#define CALLLOG(x) fprintf(stderr, (x));
*/

#define PYGAMEAPI_MASK_INTERNAL 1
#include "mask.h"

#include "pygame.h"

#include "pgcompat.h"

#include "doc/mask_doc.h"

#include "structmember.h"

#include <math.h>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

/* Macro to create mask objects. This will call the type's tp_new and tp_init.
 * Params:
 *     w: width of mask
 *     h: height of mask
 *     f: fill, 1 is used to set all the bits (to 1) and 0 is used to clear
 *        all the bits (to 0)
 */
#define CREATE_MASK_OBJ(w, h, f)                                             \
    (pgMaskObject *)PyObject_CallFunction((PyObject *)&pgMask_Type, "(ii)i", \
                                          (w), (h), (f))

/* Prototypes */
static PyTypeObject pgMask_Type;
static PG_INLINE pgMaskObject *
create_mask_using_bitmask(bitmask_t *bitmask);
static PG_INLINE pgMaskObject *
create_mask_using_bitmask_and_type(bitmask_t *bitmask, PyTypeObject *ob_type);

/********** mask helper functions **********/

/* Calculate the absolute difference between 2 Uint32s. */
static PG_INLINE Uint32
abs_diff_uint32(Uint32 a, Uint32 b)
{
    return (a > b) ? a - b : b - a;
}

/********** mask object methods **********/

/* Copies the given mask. */
static PyObject *
mask_copy(PyObject *self, PyObject *_null)
{
    bitmask_t *new_bitmask = bitmask_copy(pgMask_AsBitmap(self));

    if (NULL == new_bitmask) {
        return RAISE(PyExc_MemoryError, "cannot allocate memory for bitmask");
    }

    return (PyObject *)create_mask_using_bitmask_and_type(new_bitmask,
                                                          Py_TYPE(self));
}

/* Redirects mask.copy() to mask.__copy__(). This is done to allow
 * subclasses that override the __copy__() method to also override the copy()
 * method automatically. */
static PyObject *
mask_call_copy(PyObject *self, PyObject *_null)
{
    return PyObject_CallMethodObjArgs(self, PyUnicode_FromString("__copy__"),
                                      NULL);
}

static PyObject *
mask_get_size(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    return Py_BuildValue("(ii)", mask->w, mask->h);
}

/* Creates a Rect object based on the given mask's size. The rect's
 * attributes can be altered via the kwargs.
 *
 * Returns:
 *     Rect object or NULL to indicate a fail
 *
 * Ref: src_c/surface.c surf_get_rect()
 */
static PyObject *
mask_get_rect(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *rect = NULL;
    bitmask_t *bitmask = pgMask_AsBitmap(self);

    if (0 != PyTuple_GET_SIZE(args)) {
        return RAISE(PyExc_TypeError,
                     "get_rect only supports keyword arguments");
    }

    rect = pgRect_New4(0, 0, bitmask->w, bitmask->h);

    if (NULL == rect) {
        return RAISE(PyExc_MemoryError, "cannot allocate memory for rect");
    }

    if (NULL != kwargs) {
        PyObject *key = NULL, *value = NULL;
        Py_ssize_t pos = 0;

        while (PyDict_Next(kwargs, &pos, &key, &value)) {
            if ((-1 == PyObject_SetAttr(rect, key, value))) {
                Py_DECREF(rect);
                return NULL;
            }
        }
    }

    return rect;
}

static PyObject *
mask_get_at(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    int x, y, val;
    PyObject *pos = NULL;
    static char *keywords[] = {"pos", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", keywords, &pos))
        return NULL;

    if (!pg_TwoIntsFromObj(pos, &x, &y)) {
        return RAISE(PyExc_TypeError, "pos must be two numbers");
    }

    if (x >= 0 && x < mask->w && y >= 0 && y < mask->h) {
        val = bitmask_getbit(mask, x, y);
    }
    else {
        PyErr_Format(PyExc_IndexError, "%d, %d is out of bounds", x, y);
        return NULL;
    }

    return PyLong_FromLong(val);
}

static PyObject *
mask_set_at(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    int x, y, value = 1;
    PyObject *pos = NULL;
    static char *keywords[] = {"pos", "value", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i", keywords, &pos,
                                     &value))
        return NULL;

    if (!pg_TwoIntsFromObj(pos, &x, &y)) {
        return RAISE(PyExc_TypeError, "pos must be two numbers");
    }

    if (x >= 0 && x < mask->w && y >= 0 && y < mask->h) {
        if (value) {
            bitmask_setbit(mask, x, y);
        }
        else {
            bitmask_clearbit(mask, x, y);
        }
    }
    else {
        PyErr_Format(PyExc_IndexError, "%d, %d is out of bounds", x, y);
        return NULL;
    }
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
mask_overlap(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    bitmask_t *othermask;
    PyObject *maskobj;
    int x, y, val;
    int xp, yp;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", keywords,
                                     &pgMask_Type, &maskobj, &offset))
        return NULL;

    othermask = pgMask_AsBitmap(maskobj);

    if (!pg_TwoIntsFromObj(offset, &x, &y)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    val = bitmask_overlap_pos(mask, othermask, x, y, &xp, &yp);
    if (val) {
        return Py_BuildValue("(ii)", xp, yp);
    }
    else {
        Py_INCREF(Py_None);
        return Py_None;
    }
}

static PyObject *
mask_overlap_area(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    bitmask_t *othermask;
    PyObject *maskobj;
    int x, y, val;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", keywords,
                                     &pgMask_Type, &maskobj, &offset)) {
        return NULL;
    }

    othermask = pgMask_AsBitmap(maskobj);

    if (!pg_TwoIntsFromObj(offset, &x, &y)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    val = bitmask_overlap_area(mask, othermask, x, y);
    return PyLong_FromLong(val);
}

static PyObject *
mask_overlap_mask(PyObject *self, PyObject *args, PyObject *kwargs)
{
    int x, y;
    bitmask_t *bitmask = pgMask_AsBitmap(self);
    PyObject *maskobj;
    pgMaskObject *output_maskobj;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", keywords,
                                     &pgMask_Type, &maskobj, &offset)) {
        return NULL; /* Exception already set. */
    }

    output_maskobj = CREATE_MASK_OBJ(bitmask->w, bitmask->h, 0);

    if (!pg_TwoIntsFromObj(offset, &x, &y)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    if (NULL == output_maskobj) {
        return NULL; /* Exception already set. */
    }

    bitmask_overlap_mask(bitmask, pgMask_AsBitmap(maskobj),
                         output_maskobj->mask, x, y);

    return (PyObject *)output_maskobj;
}

static PyObject *
mask_fill(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);

    bitmask_fill(mask);

    Py_RETURN_NONE;
}

static PyObject *
mask_clear(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);

    bitmask_clear(mask);

    Py_RETURN_NONE;
}

static PyObject *
mask_invert(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);

    bitmask_invert(mask);

    Py_RETURN_NONE;
}

static PyObject *
mask_scale(PyObject *self, PyObject *args, PyObject *kwargs)
{
    int x, y;
    bitmask_t *bitmask = NULL;
    PyObject *scale = NULL;
    static char *keywords[] = {"scale", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", keywords, &scale)) {
        return NULL; /* Exception already set. */
    }

    if (!pg_TwoIntsFromObj(scale, &x, &y)) {
        return RAISE(PyExc_TypeError, "scale must be two numbers");
    }

    if (x < 0 || y < 0) {
        return RAISE(PyExc_ValueError, "cannot scale mask to negative size");
    }

    bitmask = bitmask_scale(pgMask_AsBitmap(self), x, y);

    if (NULL == bitmask) {
        return RAISE(PyExc_MemoryError, "cannot allocate memory for bitmask");
    }

    return (PyObject *)create_mask_using_bitmask(bitmask);
}

static PyObject *
mask_draw(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    bitmask_t *othermask;
    PyObject *maskobj;
    int x, y;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", keywords,
                                     &pgMask_Type, &maskobj, &offset)) {
        return NULL;
    }

    if (!pg_TwoIntsFromObj(offset, &x, &y)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    othermask = pgMask_AsBitmap(maskobj);

    bitmask_draw(mask, othermask, x, y);

    Py_RETURN_NONE;
}

static PyObject *
mask_erase(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    bitmask_t *othermask;
    PyObject *maskobj;
    int x, y;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O", keywords,
                                     &pgMask_Type, &maskobj, &offset)) {
        return NULL;
    }

    if (!pg_TwoIntsFromObj(offset, &x, &y)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    othermask = pgMask_AsBitmap(maskobj);

    bitmask_erase(mask, othermask, x, y);

    Py_RETURN_NONE;
}

static PyObject *
mask_count(PyObject *self, PyObject *_null)
{
    bitmask_t *m = pgMask_AsBitmap(self);

    return PyLong_FromLong(bitmask_count(m));
}

static PyObject *
mask_centroid(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    int x, y;
    long int m10, m01, m00;
    PyObject *xobj, *yobj;

    m10 = m01 = m00 = 0;

    for (x = 0; x < mask->w; x++) {
        for (y = 0; y < mask->h; y++) {
            if (bitmask_getbit(mask, x, y)) {
                m10 += x;
                m01 += y;
                m00++;
            }
        }
    }

    if (m00) {
        xobj = PyLong_FromLong(m10 / m00);
        yobj = PyLong_FromLong(m01 / m00);
    }
    else {
        xobj = PyLong_FromLong(0);
        yobj = PyLong_FromLong(0);
    }

    return Py_BuildValue("(NN)", xobj, yobj);
}

static PyObject *
mask_angle(PyObject *self, PyObject *_null)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    int x, y;
    long int m10, m01, m00, m20, m02, m11;

    m10 = m01 = m00 = m20 = m02 = m11 = 0;

    for (x = 0; x < mask->w; x++) {
        for (y = 0; y < mask->h; y++) {
            if (bitmask_getbit(mask, x, y)) {
                m10 += x;
                m20 += (long)x * x;
                m11 += (long)x * y;
                m02 += (long)y * y;
                m01 += y;
                m00++;
            }
        }
    }

    if (m00) {
        int xc = m10 / m00;
        int yc = m01 / m00;
        double theta =
            -90.0 *
            atan2(2 * (m11 / m00 - (long)xc * yc),
                  (m20 / m00 - (long)xc * xc) - (m02 / m00 - (long)yc * yc)) /
            M_PI;
        return PyFloat_FromDouble(theta);
    }
    else {
        return PyFloat_FromDouble(0);
    }
}

static PyObject *
mask_outline(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *c = pgMask_AsBitmap(self);
    bitmask_t *m = NULL;
    PyObject *plist = NULL;
    PyObject *value = NULL;
    int x, y, firstx, firsty, secx, secy, currx, curry, nextx, nexty, n;
    int e, every = 1;
    int a[] = {1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1};
    int b[] = {0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1};
    static char *keywords[] = {"every", NULL};

    firstx = firsty = secx = x = 0;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", keywords, &every)) {
        return NULL;
    }

    plist = PyList_New(0);
    if (!plist) {
        return RAISE(PyExc_MemoryError,
                     "outline cannot allocate memory for list");
    }

    if (!c->w || !c->h) {
        return plist;
    }

    /* Copying to a larger mask to avoid border checking. */
    m = bitmask_create(c->w + 2, c->h + 2);
    if (!m) {
        Py_DECREF(plist);
        return RAISE(PyExc_MemoryError,
                     "outline cannot allocate memory for mask");
    }

    bitmask_draw(m, c, 1, 1);

    /* find the first set pixel in the mask */
    for (y = 1; y < m->h - 1; y++) {
        for (x = 1; x < m->w - 1; x++) {
            if (bitmask_getbit(m, x, y)) {
                firstx = x;
                firsty = y;
                value = Py_BuildValue("(ii)", x - 1, y - 1);

                if (NULL == value) {
                    Py_DECREF(plist);
                    bitmask_free(m);

                    return NULL; /* Exception already set. */
                }

                if (0 != PyList_Append(plist, value)) {
                    Py_DECREF(value);
                    Py_DECREF(plist);
                    bitmask_free(m);

                    return NULL; /* Exception already set. */
                }

                Py_DECREF(value);
                break;
            }
        }
        if (bitmask_getbit(m, x, y))
            break;
    }

    /* covers the mask having zero pixels set or only the final pixel */
    if ((x == m->w - 1) && (y == m->h - 1)) {
        bitmask_free(m);
        return plist;
    }

    e = every;

    /* check just the first pixel for neighbors */
    for (n = 0; n < 8; n++) {
        if (bitmask_getbit(m, x + a[n], y + b[n])) {
            currx = secx = x + a[n];
            curry = secy = y + b[n];
            e--;
            if (!e) {
                e = every;
                value = Py_BuildValue("(ii)", secx - 1, secy - 1);

                if (NULL == value) {
                    Py_DECREF(plist);
                    bitmask_free(m);

                    return NULL; /* Exception already set. */
                }

                if (0 != PyList_Append(plist, value)) {
                    Py_DECREF(value);
                    Py_DECREF(plist);
                    bitmask_free(m);

                    return NULL; /* Exception already set. */
                }

                Py_DECREF(value);
            }
            break;
        }
    }

    /* if there are no neighbors, return */
    if (!secx) {
        bitmask_free(m);
        return plist;
    }

    /* the outline tracing loop */
    for (;;) {
        /* look around the pixel, it has to have a neighbor */
        for (n = (n + 6) & 7;; n++) {
            if (bitmask_getbit(m, currx + a[n], curry + b[n])) {
                nextx = currx + a[n];
                nexty = curry + b[n];
                e--;
                if (!e) {
                    e = every;
                    if ((curry == firsty && currx == firstx) &&
                        (secx == nextx && secy == nexty)) {
                        break;
                    }

                    value = Py_BuildValue("(ii)", nextx - 1, nexty - 1);

                    if (NULL == value) {
                        Py_DECREF(plist);
                        bitmask_free(m);

                        return NULL; /* Exception already set. */
                    }

                    if (0 != PyList_Append(plist, value)) {
                        Py_DECREF(value);
                        Py_DECREF(plist);
                        bitmask_free(m);

                        return NULL; /* Exception already set. */
                    }

                    Py_DECREF(value);
                }
                break;
            }
        }
        /* if we are back at the first pixel, and the next one will be the
           second one we visited, we are done */
        if ((curry == firsty && currx == firstx) &&
            (secx == nextx && secy == nexty)) {
            break;
        }

        curry = nexty;
        currx = nextx;
    }

    bitmask_free(m);

    return plist;
}

static PyObject *
mask_convolve(PyObject *aobj, PyObject *args, PyObject *kwargs)
{
    PyObject *bobj;
    PyObject *oobj = Py_None;
    bitmask_t *a = NULL, *b = NULL;
    int xoffset = 0, yoffset = 0;
    PyObject *offset = NULL;
    static char *keywords[] = {"other", "output", "offset", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|OO", keywords,
                                     &pgMask_Type, &bobj, &oobj, &offset)) {
        return NULL; /* Exception already set. */
    }

    if (offset && !pg_TwoIntsFromObj(offset, &xoffset, &yoffset)) {
        return RAISE(PyExc_TypeError, "offset must be two numbers");
    }

    a = pgMask_AsBitmap(aobj);
    b = pgMask_AsBitmap(bobj);

    if (oobj != Py_None) {
        /* Use this mask for the output. */
        Py_INCREF(oobj);
    }
    else {
        pgMaskObject *maskobj = CREATE_MASK_OBJ(MAX(0, a->w + b->w - 1),
                                                MAX(0, a->h + b->h - 1), 0);

        if (NULL == maskobj) {
            return NULL; /* Exception already set. */
        }

        oobj = (PyObject *)maskobj;
    }

    bitmask_convolve(a, b, pgMask_AsBitmap(oobj), xoffset, yoffset);

    return oobj;
}

/* Gets the color of a given pixel.
 *
 * Params:
 *     pixel: pixel to get the color of
 *     bpp: bytes per pixel
 *
 * Returns:
 *     pixel color
 */
static PG_INLINE Uint32
get_pixel_color(Uint8 *pixel, Uint8 bpp)
{
    switch (bpp) {
        case 1:
            return *((Uint8 *)pixel);

        case 2:
            return *((Uint16 *)pixel);

        case 3:
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            return (pixel[0]) + (pixel[1] << 8) + (pixel[2] << 16);
#else  /* SDL_BIG_ENDIAN */
            return (pixel[2]) + (pixel[1] << 8) + (pixel[0] << 16);
#endif /* SDL_BIG_ENDIAN */

        default: /* case 4: */
            return *((Uint32 *)pixel);
    }
}

/* Sets the color of a given pixel.
 *
 * Params:
 *     pixel: pixel to set the color of
 *     bpp: bytes per pixel
 *     color: color to set
 *
 * Ref: src_c/draw.c set_pixel_32()
 */
static void
set_pixel_color(Uint8 *pixel, Uint8 bpp, Uint32 color)
{
    switch (bpp) {
        case 1:
            *pixel = color;
            break;

        case 2:
            *(Uint16 *)pixel = color;
            break;

        case 3:
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            *(Uint16 *)pixel = color;
            pixel[2] = color >> 16;
#else  /* != SDL_LIL_ENDIAN */
            pixel[2] = color;
            pixel[1] = color >> 8;
            pixel[0] = color >> 16;
#endif /* SDL_LIL_ENDIAN */
            break;

        default: /* case 4: */
            *(Uint32 *)pixel = color;
            break;
    }
}

/* For each surface pixel's alpha that is greater than the threshold,
 * the corresponding bitmask bit is set.
 *
 * Params:
 *     surf: surface
 *     bitmask: bitmask to alter
 *     threshold: threshold used check surface pixels (alpha) against
 *
 * Returns:
 *     void
 */
static void
set_from_threshold(SDL_Surface *surf, bitmask_t *bitmask, int threshold)
{
    SDL_PixelFormat *format = surf->format;
    Uint8 bpp = format->BytesPerPixel;
    Uint8 *pixel = NULL;
    Uint8 rgba[4];
    int x, y;

    for (y = 0; y < surf->h; ++y) {
        pixel = (Uint8 *)surf->pixels + y * surf->pitch;

        for (x = 0; x < surf->w; ++x, pixel += bpp) {
            SDL_GetRGBA(get_pixel_color(pixel, bpp), format, rgba, rgba + 1,
                        rgba + 2, rgba + 3);
            if (rgba[3] > threshold) {
                bitmask_setbit(bitmask, x, y);
            }
        }
    }
}

/* For each surface pixel's color that is not equal to the colorkey, the
 * corresponding bitmask bit is set.
 *
 * Params:
 *     surf: surface
 *     bitmask: bitmask to alter
 *     colorkey: color used to check surface pixels against
 *
 * Returns:
 *     void
 */
static void
set_from_colorkey(SDL_Surface *surf, bitmask_t *bitmask, Uint32 colorkey)
{
    Uint8 bpp = surf->format->BytesPerPixel;
    Uint8 *pixel = NULL;
    int x, y;

    for (y = 0; y < surf->h; ++y) {
        pixel = (Uint8 *)surf->pixels + y * surf->pitch;

        for (x = 0; x < surf->w; ++x, pixel += bpp) {
            if (get_pixel_color(pixel, bpp) != colorkey) {
                bitmask_setbit(bitmask, x, y);
            }
        }
    }
}

/* Creates a mask from a given surface.
 *
 * Returns:
 *     Mask object or NULL to indicate a fail
 */
static PyObject *
mask_from_surface(PyObject *self, PyObject *args, PyObject *kwargs)
{
    SDL_Surface *surf = NULL;
    pgSurfaceObject *surfobj;
    pgMaskObject *maskobj = NULL;
    Uint32 colorkey;
    int threshold = 127; /* default value */
    int use_thresh = 1;
    static char *keywords[] = {"surface", "threshold", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|i", keywords,
                                     &pgSurface_Type, &surfobj, &threshold)) {
        return NULL; /* Exception already set. */
    }

    surf = pgSurface_AsSurface(surfobj);

    if (!surf)
        return RAISE(pgExc_SDLError, "display Surface quit");

    if (surf->w < 0 || surf->h < 0) {
        return RAISE(PyExc_ValueError,
                     "cannot create mask with negative size");
    }

    maskobj = CREATE_MASK_OBJ(surf->w, surf->h, 0);

    if (NULL == maskobj) {
        return NULL; /* Exception already set. */
    }

    if (surf->w == 0 || surf->h == 0) {
        /* Nothing left to do for 0 sized surfaces. */
        return (PyObject *)maskobj;
    }

    if (!pgSurface_Lock(surfobj)) {
        Py_DECREF((PyObject *)maskobj);
        return RAISE(PyExc_RuntimeError, "cannot lock surface");
    }

    Py_BEGIN_ALLOW_THREADS; /* Release the GIL. */

    use_thresh = (SDL_GetColorKey(surf, &colorkey) == -1);

    if (use_thresh) {
        set_from_threshold(surf, maskobj->mask, threshold);
    }
    else {
        set_from_colorkey(surf, maskobj->mask, colorkey);
    }

    Py_END_ALLOW_THREADS; /* Obtain the GIL. */

    if (!pgSurface_Unlock(surfobj)) {
        Py_DECREF((PyObject *)maskobj);
        return RAISE(PyExc_RuntimeError, "cannot unlock surface");
    }

    return (PyObject *)maskobj;
}

/*

palette_colors - this only affects surfaces with a palette
    if true we look at the colors from the palette,
    otherwise we threshold the pixel values.  This is useful if
    the surface is actually greyscale colors, and not palette colors.

*/

void
bitmask_threshold(bitmask_t *m, SDL_Surface *surf, SDL_Surface *surf2,
                  Uint32 color, Uint32 threshold, int palette_colors)
{
    int x, y, rshift, gshift, bshift, rshift2, gshift2, bshift2;
    int rloss, gloss, bloss, rloss2, gloss2, bloss2;
    Uint8 *pixels, *pixels2;
    SDL_PixelFormat *format, *format2;
    Uint32 the_color, the_color2, rmask, gmask, bmask, rmask2, gmask2, bmask2;
    Uint8 *pix;
    Uint8 r, g, b, a;
    Uint8 tr, tg, tb, ta;
    int bpp1, bpp2;

    format = surf->format;
    rmask = format->Rmask;
    gmask = format->Gmask;
    bmask = format->Bmask;
    rshift = format->Rshift;
    gshift = format->Gshift;
    bshift = format->Bshift;
    rloss = format->Rloss;
    gloss = format->Gloss;
    bloss = format->Bloss;
    bpp1 = surf->format->BytesPerPixel;

    if (surf2) {
        format2 = surf2->format;
        rmask2 = format2->Rmask;
        gmask2 = format2->Gmask;
        bmask2 = format2->Bmask;
        rshift2 = format2->Rshift;
        gshift2 = format2->Gshift;
        bshift2 = format2->Bshift;
        rloss2 = format2->Rloss;
        gloss2 = format2->Gloss;
        bloss2 = format2->Bloss;
        pixels2 = (Uint8 *)surf2->pixels;
        bpp2 = surf->format->BytesPerPixel;
    }
    else { /* make gcc stop complaining */
        rmask2 = gmask2 = bmask2 = 0;
        rshift2 = gshift2 = bshift2 = 0;
        rloss2 = gloss2 = bloss2 = 0;
        format2 = NULL;
        pixels2 = NULL;
        bpp2 = 0;
    }

    SDL_GetRGBA(color, format, &r, &g, &b, &a);
    SDL_GetRGBA(threshold, format, &tr, &tg, &tb, &ta);

    for (y = 0; y < surf->h; y++) {
        pixels = (Uint8 *)surf->pixels + y * surf->pitch;
        if (surf2) {
            pixels2 = (Uint8 *)surf2->pixels + y * surf2->pitch;
        }
        for (x = 0; x < surf->w; x++) {
            /* the_color = surf->get_at(x,y) */
            switch (bpp1) {
                case 1:
                    the_color = (Uint32) * ((Uint8 *)pixels);
                    pixels++;
                    break;
                case 2:
                    the_color = (Uint32) * ((Uint16 *)pixels);
                    pixels += 2;
                    break;
                case 3:
                    pix = ((Uint8 *)pixels);
                    pixels += 3;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                    the_color = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
                    the_color = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
                    break;
                default: /* case 4: */
                    the_color = *((Uint32 *)pixels);
                    pixels += 4;
                    break;
            }

            if (surf2) {
                switch (bpp2) {
                    case 1:
                        the_color2 = (Uint32) * ((Uint8 *)pixels2);
                        pixels2++;
                        break;
                    case 2:
                        the_color2 = (Uint32) * ((Uint16 *)pixels2);
                        pixels2 += 2;
                        break;
                    case 3:
                        pix = ((Uint8 *)pixels2);
                        pixels2 += 3;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                        the_color2 = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
                        the_color2 = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
                        break;
                    default: /* case 4: */
                        the_color2 = *((Uint32 *)pixels2);
                        pixels2 += 4;
                        break;
                }
                /* TODO: will need to handle surfaces with palette colors.
                 */
                if ((bpp2 == 1) && (bpp1 == 1) && (!palette_colors)) {
                    /* Don't look at the color of the surface, just use the
                       value. This is useful for 8bit images that aren't
                       actually using the palette.
                    */
                    if (abs_diff_uint32(the_color2, the_color) < tr) {
                        /* this pixel is within the threshold of othersurface.
                         */
                        bitmask_setbit(m, x, y);
                    }
                }
                else if ((abs_diff_uint32(
                              (((the_color2 & rmask2) >> rshift2) << rloss2),
                              (((the_color & rmask) >> rshift) << rloss)) <
                          tr) &&
                         (abs_diff_uint32(
                              (((the_color2 & gmask2) >> gshift2) << gloss2),
                              (((the_color & gmask) >> gshift) << gloss)) <
                          tg) &&
                         (abs_diff_uint32(
                              (((the_color2 & bmask2) >> bshift2) << bloss2),
                              (((the_color & bmask) >> bshift) << bloss)) <
                          tb)) {
                    /* this pixel is within the threshold of othersurface. */
                    bitmask_setbit(m, x, y);
                }

                /* TODO: will need to handle surfaces with palette colors.
                   TODO: will need to handle the case where palette_colors == 0
                */
            }
            else if ((abs_diff_uint32(
                          (((the_color & rmask) >> rshift) << rloss), r) <
                      tr) &&
                     (abs_diff_uint32(
                          (((the_color & gmask) >> gshift) << gloss), g) <
                      tg) &&
                     (abs_diff_uint32(
                          (((the_color & bmask) >> bshift) << bloss), b) <
                      tb)) {
                /* this pixel is within the threshold of the color. */
                bitmask_setbit(m, x, y);
            }
        }
    }
}

static PyObject *
mask_from_threshold(PyObject *self, PyObject *args, PyObject *kwargs)
{
    pgSurfaceObject *surfobj;
    pgSurfaceObject *surfobj2 = NULL;
    pgMaskObject *maskobj = NULL;
    SDL_Surface *surf = NULL, *surf2 = NULL;
    PyObject *rgba_obj_color, *rgba_obj_threshold = NULL;
    Uint8 rgba_color[4];
    Uint8 rgba_threshold[4] = {0, 0, 0, 255};
    Uint32 color;
    Uint32 color_threshold;
    int palette_colors = 1;
    static char *keywords[] = {"surface",      "color",          "threshold",
                               "othersurface", "palette_colors", NULL};

    if (!PyArg_ParseTupleAndKeywords(
            args, kwargs, "O!O|OO!i", keywords, &pgSurface_Type, &surfobj,
            &rgba_obj_color, &rgba_obj_threshold, &pgSurface_Type, &surfobj2,
            &palette_colors))
        return NULL;

    surf = pgSurface_AsSurface(surfobj);
    if (!surf)
        return RAISE(pgExc_SDLError, "display Surface quit");
    if (surfobj2) {
        surf2 = pgSurface_AsSurface(surfobj2);
        if (!surf2)
            return RAISE(pgExc_SDLError, "display Surface quit");
    }

    if (PyLong_Check(rgba_obj_color)) {
        color = (Uint32)PyLong_AsLong(rgba_obj_color);
    }
    else if (PyLong_Check(rgba_obj_color)) {
        color = (Uint32)PyLong_AsUnsignedLong(rgba_obj_color);
    }
    else if (pg_RGBAFromColorObj(rgba_obj_color, rgba_color)) {
        color = SDL_MapRGBA(surf->format, rgba_color[0], rgba_color[1],
                            rgba_color[2], rgba_color[3]);
    }
    else {
        return RAISE(PyExc_TypeError, "invalid color argument");
    }

    if (rgba_obj_threshold) {
        if (PyLong_Check(rgba_obj_threshold))
            color_threshold = (Uint32)PyLong_AsLong(rgba_obj_threshold);
        else if (PyLong_Check(rgba_obj_threshold))
            color_threshold =
                (Uint32)PyLong_AsUnsignedLong(rgba_obj_threshold);
        else if (pg_RGBAFromColorObj(rgba_obj_threshold, rgba_threshold))
            color_threshold =
                SDL_MapRGBA(surf->format, rgba_threshold[0], rgba_threshold[1],
                            rgba_threshold[2], rgba_threshold[3]);
        else
            return RAISE(PyExc_TypeError, "invalid threshold argument");
    }
    else {
        color_threshold =
            SDL_MapRGBA(surf->format, rgba_threshold[0], rgba_threshold[1],
                        rgba_threshold[2], rgba_threshold[3]);
    }

    maskobj = CREATE_MASK_OBJ(surf->w, surf->h, 0);

    if (NULL == maskobj) {
        return NULL; /* Exception already set. */
    }

    pgSurface_Lock(surfobj);
    if (surfobj2) {
        pgSurface_Lock(surfobj2);
    }

    Py_BEGIN_ALLOW_THREADS;
    bitmask_threshold(maskobj->mask, surf, surf2, color, color_threshold,
                      palette_colors);
    Py_END_ALLOW_THREADS;

    pgSurface_Unlock(surfobj);
    if (surfobj2) {
        pgSurface_Unlock(surfobj2);
    }

    return (PyObject *)maskobj;
}

/* The initial labelling phase of the connected components algorithm.
 *
 * Connected component labeling based on the SAUF algorithm by Kesheng Wu,
 * Ekow Otoo, and Kenji Suzuki. The algorithm is best explained by their
 * paper, "Two Strategies to Speed up Connected Component Labeling Algorithms",
 * but in summary, it is a very efficient two pass method for 8-connected
 * components. It uses a decision tree to minimize the number of neighbors that
 * need to be checked. It stores equivalence information in an array based
 * union-find.
 *
 * Params:
 *     input - the input mask
 *     image - an array to store labelled pixels
 *     ufind - the union-find label equivalence array
 *     largest - an array to store the number of pixels for each label
 *
 * Returns:
 *     the highest label in the labelled image
 */
unsigned int
cc_label(bitmask_t *input, unsigned int *image, unsigned int *ufind,
         unsigned int *largest)
{
    unsigned int *buf;
    unsigned int x, y, w, h, root, aroot, croot, temp, label;

    label = 0;
    w = input->w;
    h = input->h;

    ufind[0] = 0;
    buf = image;

    /* special case for first pixel */
    if (bitmask_getbit(input, 0, 0)) { /* process for a new connected comp: */
        label++;                       /* create a new label */
        *buf = label;                  /* give the pixel the label */
        ufind[label] = label; /* put the label in the equivalence array */
        largest[label] = 1;   /* the label has 1 pixel associated with it */
    }
    else {
        *buf = 0;
    }
    buf++;

    /* special case for first row.
           Go over the first row except the first pixel.
    */
    for (x = 1; x < w; x++) {
        if (bitmask_getbit(input, x, 0)) {
            if (*(buf - 1)) { /* d label */
                *buf = *(buf - 1);
            }
            else { /* create label */
                label++;
                *buf = label;
                ufind[label] = label;
                largest[label] = 0;
            }
            largest[*buf]++;
        }
        else {
            *buf = 0;
        }
        buf++;
    }

    /* the rest of the image */
    for (y = 1; y < h; y++) {
        /* first pixel of the row */
        if (bitmask_getbit(input, 0, y)) {
            if (*(buf - w)) { /* b label */
                *buf = *(buf - w);
            }
            else if (*(buf - w + 1)) { /* c label */
                *buf = *(buf - w + 1);
            }
            else { /* create label */
                label++;
                *buf = label;
                ufind[label] = label;
                largest[label] = 0;
            }
            largest[*buf]++;
        }
        else {
            *buf = 0;
        }
        buf++;
        /* middle pixels of the row */
        for (x = 1; x < (w - 1); x++) {
            if (bitmask_getbit(input, x, y)) {
                if (*(buf - w)) { /* b label */
                    *buf = *(buf - w);
                }
                else if (*(buf - w + 1)) { /* c branch of tree */
                    if (*(buf - w - 1)) {  /* union(c, a) */
                        croot = root = *(buf - w + 1);
                        while (ufind[root] < root) { /* find root */
                            root = ufind[root];
                        }
                        if (croot != *(buf - w - 1)) {
                            temp = aroot = *(buf - w - 1);
                            while (ufind[aroot] < aroot) { /* find root */
                                aroot = ufind[aroot];
                            }
                            if (root > aroot) {
                                root = aroot;
                            }
                            while (ufind[temp] > root) { /* set root */
                                aroot = ufind[temp];
                                ufind[temp] = root;
                                temp = aroot;
                            }
                        }
                        while (ufind[croot] > root) { /* set root */
                            temp = ufind[croot];
                            ufind[croot] = root;
                            croot = temp;
                        }
                        *buf = root;
                    }
                    else if (*(buf - 1)) { /* union(c, d) */
                        croot = root = *(buf - w + 1);
                        while (ufind[root] < root) { /* find root */
                            root = ufind[root];
                        }
                        if (croot != *(buf - 1)) {
                            temp = aroot = *(buf - 1);
                            while (ufind[aroot] < aroot) { /* find root */
                                aroot = ufind[aroot];
                            }
                            if (root > aroot) {
                                root = aroot;
                            }
                            while (ufind[temp] > root) { /* set root */
                                aroot = ufind[temp];
                                ufind[temp] = root;
                                temp = aroot;
                            }
                        }
                        while (ufind[croot] > root) { /* set root */
                            temp = ufind[croot];
                            ufind[croot] = root;
                            croot = temp;
                        }
                        *buf = root;
                    }
                    else { /* c label */
                        *buf = *(buf - w + 1);
                    }
                }
                else if (*(buf - w - 1)) { /* a label */
                    *buf = *(buf - w - 1);
                }
                else if (*(buf - 1)) { /* d label */
                    *buf = *(buf - 1);
                }
                else { /* create label */
                    label++;
                    *buf = label;
                    ufind[label] = label;
                    largest[label] = 0;
                }
                largest[*buf]++;
            }
            else {
                *buf = 0;
            }
            buf++;
        }
        /* last pixel of the row, if its not also the first pixel of the row */
        if (w > 1) {
            if (bitmask_getbit(input, x, y)) {
                if (*(buf - w)) { /* b label */
                    *buf = *(buf - w);
                }
                else if (*(buf - w - 1)) { /* a label */
                    *buf = *(buf - w - 1);
                }
                else if (*(buf - 1)) { /* d label */
                    *buf = *(buf - 1);
                }
                else { /* create label */
                    label++;
                    *buf = label;
                    ufind[label] = label;
                    largest[label] = 0;
                }
                largest[*buf]++;
            }
            else {
                *buf = 0;
            }
            buf++;
        }
    }

    return label;
}

/* Creates a bounding rect for each connected component in the given mask.
 *
 * Allocates memory for rects.
 *
 * NOTE: Caller is responsible for freeing the "ret_rects" memory.
 *
 * Params:
 *     input - mask to search in for the connected components to bound
 *     num_bounding_boxes - passes back the number of bounding rects found
 *     ret_rects - passes back the bounding rects that are found with the first
 *         rect at index 1, memory is allocated
 *
 * Returns:
 *     0 on success
 *     -2 on memory allocation error
 */
static int
get_bounding_rects(bitmask_t *input, int *num_bounding_boxes,
                   SDL_Rect **ret_rects)
{
    unsigned int *image, *ufind, *largest, *buf;
    unsigned int x_uf, label = 0;
    int x, y, w, h, temp, relabel;
    SDL_Rect *rects;

    rects = NULL;

    w = input->w;
    h = input->h;

    if (!w || !h) {
        *ret_rects = rects;
        return 0;
    }
    /* a temporary image to assign labels to each bit of the mask */
    image = (unsigned int *)malloc(sizeof(unsigned int) * w * h);
    if (!image) {
        return -2;
    }

    /* allocate enough space for the maximum possible connected components */
    /* the union-find array. see wikipedia for info on union find */
    ufind = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                   (h / 2 + 1));
    if (!ufind) {
        free(image);
        return -2;
    }

    largest = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                     (h / 2 + 1));
    if (!largest) {
        free(image);
        free(ufind);
        return -2;
    }

    /* do the initial labelling */
    label = cc_label(input, image, ufind, largest);

    relabel = 0;
    /* flatten and relabel the union-find equivalence array.  Start at label 1
       because label 0 indicates an unset pixel.  For this reason, we also use
       <= label rather than < label. */
    for (x_uf = 1; x_uf <= label; ++x_uf) {
        if (ufind[x_uf] < x_uf) {             /* is it a union find root? */
            ufind[x_uf] = ufind[ufind[x_uf]]; /* relabel it to its root */
        }
        else { /* its a root */
            relabel++;
            ufind[x_uf] = relabel; /* assign the lowest label available */
        }
    }

    *num_bounding_boxes = relabel;

    if (relabel == 0) {
        /* early out, as we didn't find anything. */
        free(image);
        free(ufind);
        free(largest);
        *ret_rects = rects;
        return 0;
    }

    /* the bounding rects, need enough space for the number of labels */
    rects = (SDL_Rect *)malloc(sizeof(SDL_Rect) * (relabel + 1));
    if (!rects) {
        free(image);
        free(ufind);
        free(largest);
        return -2;
    }

    for (temp = 0; temp <= relabel; temp++) {
        rects[temp].h = 0; /* so we know if its a new rect or not */
    }

    /* find the bounding rect of each connected component */
    buf = image;
    for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++) {
            if (ufind[*buf]) { /* if the pixel is part of a component */
                if (rects[ufind[*buf]].h) { /* the component has a rect */
                    temp = rects[ufind[*buf]].x;
                    rects[ufind[*buf]].x = MIN(x, temp);
                    rects[ufind[*buf]].y = MIN(y, rects[ufind[*buf]].y);
                    rects[ufind[*buf]].w =
                        MAX(rects[ufind[*buf]].w + temp, x + 1) -
                        rects[ufind[*buf]].x;
                    rects[ufind[*buf]].h = MAX(rects[ufind[*buf]].h,
                                               y - rects[ufind[*buf]].y + 1);
                }
                else { /* otherwise, start the rect */
                    rects[ufind[*buf]].x = x;
                    rects[ufind[*buf]].y = y;
                    rects[ufind[*buf]].w = 1;
                    rects[ufind[*buf]].h = 1;
                }
            }
            buf++;
        }
    }

    free(image);
    free(ufind);
    free(largest);
    *ret_rects = rects;

    return 0;
}

static PyObject *
mask_get_bounding_rects(PyObject *self, PyObject *_null)
{
    SDL_Rect *regions;
    SDL_Rect *aregion;
    int num_bounding_boxes, i, r;
    PyObject *rect_list;
    PyObject *rect;

    bitmask_t *mask = pgMask_AsBitmap(self);

    rect_list = NULL;
    regions = NULL;
    aregion = NULL;

    num_bounding_boxes = 0;

    Py_BEGIN_ALLOW_THREADS;

    r = get_bounding_rects(mask, &num_bounding_boxes, &regions);

    Py_END_ALLOW_THREADS;

    if (r == -2) {
        /* memory out failure */
        return RAISE(PyExc_MemoryError,
                     "Not enough memory to get bounding rects. \n");
    }

    rect_list = PyList_New(0);

    if (!rect_list) {
        free(regions);

        return NULL; /* Exception already set. */
    }

    /* build a list of rects to return.  Starts at 1 because we never use 0. */
    for (i = 1; i <= num_bounding_boxes; i++) {
        aregion = regions + i;
        rect = pgRect_New4(aregion->x, aregion->y, aregion->w, aregion->h);

        if (NULL == rect) {
            Py_DECREF(rect_list);
            free(regions);

            return RAISE(PyExc_MemoryError,
                         "cannot allocate memory for bounding rects");
        }

        if (0 != PyList_Append(rect_list, rect)) {
            Py_DECREF(rect);
            Py_DECREF(rect_list);
            free(regions);

            return NULL; /* Exception already set. */
        }

        Py_DECREF(rect);
    }

    free(regions);

    return rect_list;
}

/* Finds all the connected components in a given mask.
 *
 * Allocates memory for components.
 *
 * NOTE: Caller is responsible for freeing the "components" memory.
 *
 * Params:
 *     mask - mask to search in for the connected components
 *     components - passes back an array of connected component masks with the
 *         first component at index 1, memory is allocated
 *     min - minimum number of pixels for a component to be considered,
 *         defaults to 0 for negative values
 *
 * Returns:
 *     the number of connected components (>= 0)
 *     -2 on memory allocation error
 */
static int
get_connected_components(bitmask_t *mask, bitmask_t ***components, int min)
{
    unsigned int *image, *ufind, *largest, *buf;
    unsigned int x_uf, min_cc, label = 0;
    int x, y, w, h, relabel;
    bitmask_t **comps;

    w = mask->w;
    h = mask->h;

    if (!w || !h) {
        return 0;
    }

    /* a temporary image to assign labels to each bit of the mask */
    image = (unsigned int *)malloc(sizeof(unsigned int) * w * h);
    if (!image) {
        return -2;
    }

    /* allocate enough space for the maximum possible connected components */
    /* the union-find array. see wikipedia for info on union find */
    ufind = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                   (h / 2 + 1));
    if (!ufind) {
        free(image);
        return -2;
    }

    largest = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                     (h / 2 + 1));
    if (!largest) {
        free(image);
        free(ufind);
        return -2;
    }

    /* do the initial labelling */
    label = cc_label(mask, image, ufind, largest);

    for (x_uf = 1; x_uf <= label; ++x_uf) {
        if (ufind[x_uf] < x_uf) {
            largest[ufind[x_uf]] += largest[x_uf];
        }
    }

    relabel = 0;
    min_cc = (0 < min) ? (unsigned int)min : 0;

    /* flatten and relabel the union-find equivalence array.  Start at label 1
       because label 0 indicates an unset pixel.  For this reason, we also use
       <= label rather than < label. */
    for (x_uf = 1; x_uf <= label; ++x_uf) {
        if (ufind[x_uf] < x_uf) {             /* is it a union find root? */
            ufind[x_uf] = ufind[ufind[x_uf]]; /* relabel it to its root */
        }
        else { /* its a root */
            if (largest[x_uf] >= min_cc) {
                relabel++;
                ufind[x_uf] = relabel; /* assign the lowest label available */
            }
            else {
                ufind[x_uf] = 0;
            }
        }
    }

    if (relabel == 0) {
        /* early out, as we didn't find anything. */
        free(image);
        free(ufind);
        free(largest);
        return 0;
    }

    /* allocate space for the mask array */
    comps = (bitmask_t **)malloc(sizeof(bitmask_t *) * (relabel + 1));
    if (!comps) {
        free(image);
        free(ufind);
        free(largest);
        return -2;
    }

    /* create the empty masks */
    for (x = 1; x <= relabel; x++) {
        comps[x] = bitmask_create(w, h);
    }

    /* set the bits in each mask */
    buf = image;
    for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++) {
            if (ufind[*buf]) { /* if the pixel is part of a component */
                bitmask_setbit(comps[ufind[*buf]], x, y);
            }
            buf++;
        }
    }

    free(image);
    free(ufind);
    free(largest);

    *components = comps;

    return relabel;
}

static PyObject *
mask_connected_components(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *mask_list = NULL;
    pgMaskObject *maskobj = NULL;
    bitmask_t **components = NULL;
    bitmask_t *mask = pgMask_AsBitmap(self);
    int i, m, num_components, min = 0; /* Default min value. */
    static char *keywords[] = {"minimum", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", keywords, &min)) {
        return NULL; /* Exception already set. */
    }

    Py_BEGIN_ALLOW_THREADS;
    num_components = get_connected_components(mask, &components, min);
    Py_END_ALLOW_THREADS;

    if (num_components == -2) {
        return RAISE(PyExc_MemoryError,
                     "cannot allocate memory for connected components");
    }

    mask_list = PyList_New(0);
    if (!mask_list) {
        /* Components were allocated starting at index 1. */
        for (i = 1; i <= num_components; ++i) {
            bitmask_free(components[i]);
        }

        free(components);
        return NULL; /* Exception already set. */
    }

    /* Components were allocated starting at index 1. */
    for (i = 1; i <= num_components; ++i) {
        maskobj = create_mask_using_bitmask(components[i]);

        if (NULL == maskobj) {
            /* Starting freeing with the current index. */
            for (m = i; m <= num_components; ++m) {
                bitmask_free(components[m]);
            }

            free(components);
            Py_DECREF(mask_list);
            return NULL; /* Exception already set. */
        }

        if (0 != PyList_Append(mask_list, (PyObject *)maskobj)) {
            /* Can't append to the list. Starting freeing with the next index
             * as maskobj contains the component from the current index. */
            for (m = i + 1; m <= num_components; ++m) {
                bitmask_free(components[m]);
            }

            free(components);
            Py_DECREF((PyObject *)maskobj);
            Py_DECREF(mask_list);
            return NULL; /* Exception already set. */
        }

        Py_DECREF((PyObject *)maskobj);
    }

    free(components);
    return mask_list;
}

/* Finds the largest connected component in a given mask.
 *
 * Tracks the number of pixels in each label, finding the biggest one while
 * flattening the union-find equivalence array. It then writes an output mask
 * containing only the largest connected component.
 *
 * Params:
 *     input - mask to search in for the largest connected component
 *     output - this mask is updated with the largest connected component
 *     ccx - x index, if < 0 then the largest connected component in the input
 *         mask is found and copied to the output mask, otherwise the connected
 *         component at (ccx, ccy) is copied to the output mask
 *     ccy - y index
 *
 * Returns:
 *     0 on success
 *     -2 on memory allocation error
 */
static int
largest_connected_comp(bitmask_t *input, bitmask_t *output, int ccx, int ccy)
{
    unsigned int *image, *ufind, *largest, *buf;
    unsigned int max, x, y, w, h, label;

    w = input->w;
    h = input->h;

    if (!w || !h) {
        return 0;
    }

    /* a temporary image to assign labels to each bit of the mask */
    image = (unsigned int *)malloc(sizeof(unsigned int) * w * h);
    if (!image) {
        return -2;
    }
    /* allocate enough space for the maximum possible connected components */
    /* the union-find array. see wikipedia for info on union find */
    ufind = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                   (h / 2 + 1));
    if (!ufind) {
        free(image);
        return -2;
    }
    /* an array to track the number of pixels associated with each label */
    largest = (unsigned int *)malloc(sizeof(unsigned int) * (w / 2 + 1) *
                                     (h / 2 + 1));
    if (!largest) {
        free(image);
        free(ufind);
        return -2;
    }

    /* do the initial labelling */
    label = cc_label(input, image, ufind, largest);

    max = 1;
    /* flatten the union-find equivalence array */
    for (x = 2; x <= label; x++) {
        if (ufind[x] != x) {                 /* is it a union find root? */
            largest[ufind[x]] += largest[x]; /* add its pixels to its root */
            ufind[x] = ufind[ufind[x]];      /* relabel it to its root */
        }
        if (largest[ufind[x]] > largest[max]) { /* is it the new biggest? */
            max = ufind[x];
        }
    }

    /* write out the final image */
    buf = image;
    if (ccx >= 0)
        max = ufind[*(buf + ccy * w + ccx)];
    for (y = 0; y < h; y++) {
        for (x = 0; x < w; x++) {
            if (ufind[*buf] == max) {         /* if the label is the max one */
                bitmask_setbit(output, x, y); /* set the bit in the mask */
            }
            buf++;
        }
    }

    free(image);
    free(ufind);
    free(largest);

    return 0;
}

static PyObject *
mask_connected_component(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *input = pgMask_AsBitmap(self);
    pgMaskObject *output_maskobj = NULL;
    int x = -1, y = -1;
    Py_ssize_t args_exist = PyTuple_Size(args);
    PyObject *pos = NULL;
    static char *keywords[] = {"pos", NULL};

    if (kwargs)
        args_exist += PyDict_Size(kwargs);

    if (args_exist) {
        if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", keywords, &pos)) {
            return NULL; /* Exception already set. */
        }

        if (!pg_TwoIntsFromObj(pos, &x, &y)) {
            return RAISE(PyExc_TypeError, "pos must be two numbers");
        }

        if (x < 0 || x >= input->w || y < 0 || y >= input->h) {
            return PyErr_Format(PyExc_IndexError, "%d, %d is out of bounds", x,
                                y);
        }
    }

    output_maskobj = CREATE_MASK_OBJ(input->w, input->h, 0);

    if (NULL == output_maskobj) {
        return NULL; /* Exception already set. */
    }

    /* If a pixel index is provided and the indexed bit is not set, then the
     * returned mask is empty.
     */
    if (!args_exist || bitmask_getbit(input, x, y)) {
        if (largest_connected_comp(input, output_maskobj->mask, x, y) == -2) {
            Py_DECREF(output_maskobj);
            return RAISE(PyExc_MemoryError,
                         "cannot allocate memory for connected component");
        }
    }

    return (PyObject *)output_maskobj;
}

/* Extract the color data from a color object.
 *
 * Params:
 *     surf: surface that color will be mapped from
 *     color_obj: color object to extract color data from
 *     rbga_color: rbga array, contains default color if color_obj is NULL
 *     color: color value extracted from the color_obj (or from the default
 *         value of rbga_color)
 *
 * Returns:
 *     int: 1, means the color data extraction was successful and the color
 *             parameter contains a valid color value
 *          0, means the color data extraction has failed and an exception has
 *             been set
 */
static int
extract_color(SDL_Surface *surf, PyObject *color_obj, Uint8 rgba_color[],
              Uint32 *color)
{
    if (NULL == color_obj) {
        *color = SDL_MapRGBA(surf->format, rgba_color[0], rgba_color[1],
                             rgba_color[2], rgba_color[3]);
        return 1;
    }

    if (PyLong_Check(color_obj)) {
        long intval = PyLong_AsLong(color_obj);

        if ((-1 == intval && PyErr_Occurred()) || intval > (long)0xFFFFFFFF) {
            PyErr_SetString(PyExc_ValueError, "invalid color argument");
            return 0;
        }

        *color = (Uint32)intval;
        return 1;
    }

    if (PyLong_Check(color_obj)) {
        unsigned long longval = PyLong_AsUnsignedLong(color_obj);

        if (PyErr_Occurred() || longval > 0xFFFFFFFF) {
            PyErr_SetString(PyExc_ValueError, "invalid color argument");
            return 0;
        }

        *color = (Uint32)longval;
        return 1;
    }

    if (pg_RGBAFromFuzzyColorObj(color_obj, rgba_color)) {
        *color = SDL_MapRGBA(surf->format, rgba_color[0], rgba_color[1],
                             rgba_color[2], rgba_color[3]);
        return 1;
    }

    return 0; /* Exception already set. */
}

/* Draws a mask on a surface.
 *
 * Params:
 *     surf: surface to draw on
 *     bitmask: bitmask to draw
 *     x_dest: x position on surface of where to start drawing
 *     y_dest: y position on surface of where to start drawing
 *     draw_setbits: if non-zero then draw the set bits (bits==1)
 *     draw_unsetbits: if non-zero then draw the unset bits (bits==0)
 *     setsurf: use colors from this surface for set bits (bits==1)
 *     unsetsurf: use colors from this surface for unset bits (bits==0)
 *     setcolor: color for set bits, setsurf takes precedence (bits==1)
 *     unsetcolor: color for unset bits, unsetsurf takes precedence (bits==0)
 *
 * Assumptions:
 *     - surf and bitmask are non-NULL
 *     - all surfaces have the same pixel format
 *     - all surfaces that are non-NULL are locked
 */
static void
draw_to_surface(SDL_Surface *surf, bitmask_t *bitmask, int x_dest, int y_dest,
                int draw_setbits, int draw_unsetbits, SDL_Surface *setsurf,
                SDL_Surface *unsetsurf, Uint32 *setcolor, Uint32 *unsetcolor)
{
    Uint8 *pixel = NULL;
    Uint8 bpp;
    int x, y, x_end, y_end, x_start, y_start; /* surf indexing */
    int xm, ym, xm_start, ym_start; /* bitmask/setsurf/unsetsurf indexing */

    /* There is nothing to do when any of these conditions exist:
     * - surface has a width or height of <= 0
     * - mask has a width or height of <= 0
     * - draw_setbits and draw_unsetbits are both 0 */
    if ((surf->h <= 0) || (surf->w <= 0) || (bitmask->h <= 0) ||
        (bitmask->w <= 0) || (!draw_setbits && !draw_unsetbits)) {
        return;
    }

    /* There is also nothing to do when the destination position is such that
     * nothing will be drawn on the surface. */
    if ((x_dest >= surf->w) || (y_dest >= surf->h) || (-x_dest > bitmask->w) ||
        (-y_dest > bitmask->h)) {
        return;
    }

    bpp = surf->format->BytesPerPixel;

    xm_start = (x_dest < 0) ? -x_dest : 0;
    x_start = (x_dest > 0) ? x_dest : 0;
    x_end = MIN(surf->w, bitmask->w + x_dest);

    ym_start = (y_dest < 0) ? -y_dest : 0;
    y_start = (y_dest > 0) ? y_dest : 0;
    y_end = MIN(surf->h, bitmask->h + y_dest);

    if (NULL == setsurf && NULL == unsetsurf) {
        /* Draw just using color values. No surfaces. */
        draw_setbits = draw_setbits && NULL != setcolor;
        draw_unsetbits = draw_unsetbits && NULL != unsetcolor;

        for (y = y_start, ym = ym_start; y < y_end; ++y, ++ym) {
            pixel = (Uint8 *)surf->pixels + y * surf->pitch + x_start * bpp;

            for (x = x_start, xm = xm_start; x < x_end;
                 ++x, ++xm, pixel += bpp) {
                if (bitmask_getbit(bitmask, xm, ym)) {
                    if (draw_setbits) {
                        set_pixel_color(pixel, bpp, *setcolor);
                    }
                }
                else if (draw_unsetbits) {
                    set_pixel_color(pixel, bpp, *unsetcolor);
                }
            }
        }
    }
    else if (NULL == setcolor && NULL == unsetcolor && NULL != setsurf &&
             NULL != unsetsurf && setsurf->h + y_dest >= y_end &&
             setsurf->w + x_dest >= x_end && unsetsurf->h + y_dest >= y_end &&
             unsetsurf->w + x_dest >= x_end) {
        /* Draw using surfaces that are as big (or bigger) as what is being
         * drawn and no color values are being used. */
        Uint8 *setpixel = NULL, *unsetpixel = NULL;

        for (y = y_start, ym = ym_start; y < y_end; ++y, ++ym) {
            pixel = (Uint8 *)surf->pixels + y * surf->pitch + x_start * bpp;
            setpixel = (Uint8 *)setsurf->pixels + ym * setsurf->pitch +
                       xm_start * bpp;
            unsetpixel = (Uint8 *)unsetsurf->pixels + ym * unsetsurf->pitch +
                         xm_start * bpp;

            for (x = x_start, xm = xm_start; x < x_end;
                 ++x, ++xm, pixel += bpp, setpixel += bpp, unsetpixel += bpp) {
                if (bitmask_getbit(bitmask, xm, ym)) {
                    if (draw_setbits) {
                        set_pixel_color(pixel, bpp,
                                        get_pixel_color(setpixel, bpp));
                    }
                }
                else if (draw_unsetbits) {
                    set_pixel_color(pixel, bpp,
                                    get_pixel_color(unsetpixel, bpp));
                }
            }
        }
    }
    else {
        /* Draw using surfaces and color values. */
        Uint8 *setpixel = NULL, *unsetpixel = NULL;
        int use_setsurf, use_unsetsurf;

        /* Looping over each bit in the mask and deciding whether to use a
         * color from setsurf/unsetsurf or from setcolor/unsetcolor. */
        for (y = y_start, ym = ym_start; y < y_end; ++y, ++ym) {
            pixel = (Uint8 *)surf->pixels + y * surf->pitch + x_start * bpp;
            use_setsurf = draw_setbits && NULL != setsurf && setsurf->h > ym;
            use_unsetsurf =
                draw_unsetbits && NULL != unsetsurf && unsetsurf->h > ym;

            if (use_setsurf) {
                setpixel = (Uint8 *)setsurf->pixels + ym * setsurf->pitch +
                           xm_start * bpp;
            }

            if (use_unsetsurf) {
                unsetpixel = (Uint8 *)unsetsurf->pixels +
                             ym * unsetsurf->pitch + xm_start * bpp;
            }

            for (x = x_start, xm = xm_start; x < x_end;
                 ++x, ++xm, pixel += bpp) {
                if (bitmask_getbit(bitmask, xm, ym)) {
                    if (draw_setbits) {
                        if (use_setsurf && setsurf->w > xm) {
                            set_pixel_color(pixel, bpp,
                                            get_pixel_color(setpixel, bpp));
                        }
                        else if (NULL != setcolor) {
                            set_pixel_color(pixel, bpp, *setcolor);
                        }
                    }
                }
                else if (draw_unsetbits) {
                    if (use_unsetsurf && unsetsurf->w > xm) {
                        set_pixel_color(pixel, bpp,
                                        get_pixel_color(unsetpixel, bpp));
                    }
                    else if (NULL != unsetcolor) {
                        set_pixel_color(pixel, bpp, *unsetcolor);
                    }
                }

                if (use_setsurf) {
                    setpixel += bpp;
                }

                if (use_unsetsurf) {
                    unsetpixel += bpp;
                }
            }
        }
    }
}

/* Checks if the surfaces have the same pixel formats.
 *
 * Params:
 *     surf: surface to check against
 *     check_surf: surface to check
 *
 * Returns:
 *     int: 0 to indicate surfaces don't have the same format
 *          1 to indicate the surfaces have the same format
 *
 * Assumptions:
 *     - both parameters are non-NULL
 *     - these checks are enough to assume the pixel formats are the same
 */
static int
check_surface_pixel_format(SDL_Surface *surf, SDL_Surface *check_surf)
{
    if ((surf->format->BytesPerPixel != check_surf->format->BytesPerPixel) ||
        (surf->format->BitsPerPixel != check_surf->format->BitsPerPixel) ||
        (surf->format->format != check_surf->format->format)) {
        return 0;
    }

    return 1;
}

/* Draws a mask on a surface.
 *
 * Returns:
 *     Surface object or NULL to indicate a fail.
 */
static PyObject *
mask_to_surface(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *surfobj = Py_None, *setcolorobj = NULL, *unsetcolorobj = NULL;
    PyObject *setsurfobj = Py_None, *unsetsurfobj = Py_None;
    PyObject *destobj = NULL;
    SDL_Surface *surf = NULL, *setsurf = NULL, *unsetsurf = NULL;
    bitmask_t *bitmask = pgMask_AsBitmap(self);
    Uint32 *setcolor_ptr = NULL, *unsetcolor_ptr = NULL;
    Uint32 setcolor, unsetcolor;
    int draw_setbits = 0, draw_unsetbits = 0;
    int created_surfobj = 0; /* Set to 1 if this func creates the surfobj. */
    int x_dest = 0, y_dest = 0; /* Default destination coordinates. */
    Uint8 dflt_setcolor[] = {255, 255, 255, 255}; /* Default set color. */
    Uint8 dflt_unsetcolor[] = {0, 0, 0, 255};     /* Default unset color. */

    static char *keywords[] = {"surface",  "setsurface", "unsetsurface",
                               "setcolor", "unsetcolor", "dest",
                               NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOOOOO", keywords,
                                     &surfobj, &setsurfobj, &unsetsurfobj,
                                     &setcolorobj, &unsetcolorobj, &destobj)) {
        return NULL; /* Exception already set. */
    }

    if (Py_None == surfobj) {
        surfobj =
            PyObject_CallFunction((PyObject *)&pgSurface_Type, "(ii)ii",
                                  bitmask->w, bitmask->h, PGS_SRCALPHA, 32);

        if (NULL == surfobj) {
            if (!PyErr_Occurred()) {
                return RAISE(PyExc_RuntimeError, "unable to create surface");
            }
            return NULL;
        }

        created_surfobj = 1;
    }
    else if (!pgSurface_Check(surfobj)) {
        return RAISE(PyExc_TypeError, "invalid surface argument");
    }

    surf = pgSurface_AsSurface(surfobj);

    if (!surf)
        return RAISE(pgExc_SDLError, "display Surface quit");

    if (Py_None != setsurfobj) {
        if (!pgSurface_Check(setsurfobj)) {
            PyErr_SetString(PyExc_TypeError, "invalid setsurface argument");
            goto to_surface_error;
        }

        setsurf = pgSurface_AsSurface(setsurfobj);

        if (!setsurf)
            return RAISE(pgExc_SDLError, "display Surface quit");

        if (0 == check_surface_pixel_format(surf, setsurf)) {
            /* Needs to have the same format settings as surface. */
            PyErr_SetString(PyExc_ValueError,
                            "setsurface needs to have same "
                            "bytesize/bitsize/alpha format as surface");
            goto to_surface_error;
        }
        else if ((setsurf->h <= 0) || (setsurf->w <= 0)) {
            /* Surface has no usable color positions, so ignore it. */
            setsurf = NULL;
        }
        else {
            draw_setbits = 1;
        }
    }

    if (Py_None != unsetsurfobj) {
        if (!pgSurface_Check(unsetsurfobj)) {
            PyErr_SetString(PyExc_TypeError, "invalid unsetsurface argument");
            goto to_surface_error;
        }

        unsetsurf = pgSurface_AsSurface(unsetsurfobj);

        if (!unsetsurf)
            return RAISE(pgExc_SDLError, "display Surface quit");

        if (0 == check_surface_pixel_format(surf, unsetsurf)) {
            /* Needs to have the same format settings as surface. */
            PyErr_SetString(PyExc_ValueError,
                            "unsetsurface needs to have same "
                            "bytesize/bitsize/alpha format as surface");
            goto to_surface_error;
        }
        else if ((unsetsurf->h <= 0) || (unsetsurf->w <= 0)) {
            /* Surface has no usable color positions, so ignore it. */
            unsetsurf = NULL;
        }
        else {
            draw_unsetbits = 1;
        }
    }

    if (Py_None != setcolorobj) {
        if (!extract_color(surf, setcolorobj, dflt_setcolor, &setcolor)) {
            goto to_surface_error; /* Exception already set. */
        }

        setcolor_ptr = &setcolor;
        draw_setbits = 1;
    }

    if (Py_None != unsetcolorobj) {
        if (!extract_color(surf, unsetcolorobj, dflt_unsetcolor,
                           &unsetcolor)) {
            goto to_surface_error; /* Exception already set. */
        }

        unsetcolor_ptr = &unsetcolor;
        draw_unsetbits = 1;
    }

    if (NULL != destobj) {
        int tempx = 0, tempy = 0;

        /* Destination coordinates can be extracted from:
         * - lists/tuples with 2 items
         * - Rect (or Rect like) objects (uses x, y values) */
        if (pg_TwoIntsFromObj(destobj, &tempx, &tempy)) {
            x_dest = tempx;
            y_dest = tempy;
        }
        else {
            SDL_Rect temp_rect;
            SDL_Rect *dest_rect = pgRect_FromObject(destobj, &temp_rect);

            if (NULL != dest_rect) {
                x_dest = dest_rect->x;
                y_dest = dest_rect->y;
            }
            else {
                PyErr_SetString(PyExc_TypeError, "invalid dest argument");
                goto to_surface_error;
            }
        }
    }

    if (!pgSurface_Lock((pgSurfaceObject *)surfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot lock surface");
        goto to_surface_error;
    }

    /* Only lock the setsurface if it is being used.
     * i.e. setsurf is non-NULL */
    if (NULL != setsurf && !pgSurface_Lock((pgSurfaceObject *)setsurfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot lock setsurface");
        goto to_surface_error;
    }

    /* Only lock the unsetsurface if it is being used.
     * i.e.. unsetsurf is non-NULL. */
    if (NULL != unsetsurf &&
        !pgSurface_Lock((pgSurfaceObject *)unsetsurfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot lock unsetsurface");
        goto to_surface_error;
    }

    Py_BEGIN_ALLOW_THREADS; /* Release the GIL. */

    draw_to_surface(surf, bitmask, x_dest, y_dest, draw_setbits,
                    draw_unsetbits, setsurf, unsetsurf, setcolor_ptr,
                    unsetcolor_ptr);

    Py_END_ALLOW_THREADS; /* Obtain the GIL. */

    if (NULL != unsetsurf &&
        !pgSurface_Unlock((pgSurfaceObject *)unsetsurfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot unlock unsetsurface");
        goto to_surface_error;
    }

    if (NULL != setsurf && !pgSurface_Unlock((pgSurfaceObject *)setsurfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot unlock setsurface");
        goto to_surface_error;
    }

    if (!pgSurface_Unlock((pgSurfaceObject *)surfobj)) {
        PyErr_SetString(PyExc_RuntimeError, "cannot unlock surface");
        goto to_surface_error;
    }

    if (!created_surfobj) {
        /* Only increase ref count if this func didn't create the surfobj. */
        Py_INCREF(surfobj);
    }

    return surfobj;

/* Handles the cleanup for fail cases. */
to_surface_error:
    if (created_surfobj) {
        /* Only decrease ref count if this func created the surfobj. */
        Py_DECREF(surfobj);
    }

    return NULL;
}

static PyMethodDef mask_methods[] = {
    {"__copy__", mask_copy, METH_NOARGS, DOC_MASKCOPY},
    {"copy", mask_call_copy, METH_NOARGS, DOC_MASKCOPY},
    {"get_size", mask_get_size, METH_NOARGS, DOC_MASKGETSIZE},
    {"get_rect", (PyCFunction)mask_get_rect, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKGETRECT},
    {"get_at", (PyCFunction)mask_get_at, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKGETAT},
    {"set_at", (PyCFunction)mask_set_at, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKSETAT},
    {"overlap", (PyCFunction)mask_overlap, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKOVERLAP},
    {"overlap_area", (PyCFunction)mask_overlap_area,
     METH_VARARGS | METH_KEYWORDS, DOC_MASKOVERLAPAREA},
    {"overlap_mask", (PyCFunction)mask_overlap_mask,
     METH_VARARGS | METH_KEYWORDS, DOC_MASKOVERLAPMASK},
    {"fill", mask_fill, METH_NOARGS, DOC_MASKFILL},
    {"clear", mask_clear, METH_NOARGS, DOC_MASKCLEAR},
    {"invert", mask_invert, METH_NOARGS, DOC_MASKINVERT},
    {"scale", (PyCFunction)mask_scale, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKSCALE},
    {"draw", (PyCFunction)mask_draw, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKDRAW},
    {"erase", (PyCFunction)mask_erase, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKERASE},
    {"count", mask_count, METH_NOARGS, DOC_MASKCOUNT},
    {"centroid", mask_centroid, METH_NOARGS, DOC_MASKCENTROID},
    {"angle", mask_angle, METH_NOARGS, DOC_MASKANGLE},
    {"outline", (PyCFunction)mask_outline, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKOUTLINE},
    {"convolve", (PyCFunction)mask_convolve, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKCONVOLVE},
    {"connected_component", (PyCFunction)mask_connected_component,
     METH_VARARGS | METH_KEYWORDS, DOC_MASKCONNECTEDCOMPONENT},
    {"connected_components", (PyCFunction)mask_connected_components,
     METH_VARARGS | METH_KEYWORDS, DOC_MASKCONNECTEDCOMPONENTS},
    {"get_bounding_rects", mask_get_bounding_rects, METH_NOARGS,
     DOC_MASKGETBOUNDINGRECTS},
    {"to_surface", (PyCFunction)mask_to_surface, METH_VARARGS | METH_KEYWORDS,
     DOC_MASKTOSURFACE},

    {NULL, NULL, 0, NULL}};

/*mask object internals*/

/* This is a helper function for internal use only.
 * Creates a mask object using an existing bitmask.
 *
 * Params:
 *     bitmask: pointer to the bitmask to use
 *
 * Returns:
 *     Mask object or NULL to indicate a fail
 */
static PG_INLINE pgMaskObject *
create_mask_using_bitmask(bitmask_t *bitmask)
{
    return create_mask_using_bitmask_and_type(bitmask, &pgMask_Type);
}

/* This is a helper function for internal use only.
 * Creates a mask object using an existing bitmask and a type.
 *
 * Params:
 *     bitmask: pointer to the bitmask to use
 *     ob_type: pointer to the mask object type to create
 *
 * Returns:
 *     Mask object or NULL to indicate a fail
 */
static PG_INLINE pgMaskObject *
create_mask_using_bitmask_and_type(bitmask_t *bitmask, PyTypeObject *ob_type)
{
    /* tp_init is not needed as the bitmask has already been created. */
    pgMaskObject *maskobj =
        (pgMaskObject *)pgMask_Type.tp_new(ob_type, NULL, NULL);

    if (NULL == maskobj) {
        return (pgMaskObject *)RAISE(PyExc_MemoryError,
                                     "cannot allocate memory for mask");
    }

    maskobj->mask = bitmask;
    return maskobj;
}

static void
mask_dealloc(PyObject *self)
{
    bitmask_t *bitmask = pgMask_AsBitmap(self);

    if (NULL != bitmask) {
        /* Free up the bitmask. */
        bitmask_free(bitmask);
    }

    /* Free up the mask. */
    Py_TYPE(self)->tp_free(self);
}

static PyObject *
mask_repr(PyObject *self)
{
    bitmask_t *mask = pgMask_AsBitmap(self);
    return PyUnicode_FromFormat("<Mask(%dx%d)>", mask->w, mask->h);
}

static PyObject *
mask_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs)
{
    pgMaskObject *maskobj = (pgMaskObject *)subtype->tp_alloc(subtype, 0);

    if (NULL == maskobj) {
        return RAISE(PyExc_MemoryError, "cannot allocate memory for mask");
    }

    maskobj->mask = NULL;
    return (PyObject *)maskobj;
}

static int
mask_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
    bitmask_t *bitmask = NULL;
    PyObject *size = NULL;
    int w, h;
    int fill = 0; /* Default is false. */
    char *keywords[] = {"size", "fill", NULL};
    const char *format = "O|p";

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, format, keywords, &size,
                                     &fill)) {
        return -1;
    }

    if (!pg_TwoIntsFromObj(size, &w, &h)) {
        PyErr_SetString(PyExc_TypeError, "size must be two numbers");
        return -1;
    }

    if (w < 0 || h < 0) {
        PyErr_SetString(PyExc_ValueError,
                        "cannot create mask with negative size");
        return -1;
    }

    bitmask = bitmask_create(w, h);

    if (NULL == bitmask) {
        PyErr_SetString(PyExc_MemoryError,
                        "cannot allocate memory for bitmask");
        return -1;
    }

    if (fill) {
        bitmask_fill(bitmask);
    }

    ((pgMaskObject *)self)->mask = bitmask;
    return 0;
}

typedef struct {
    int numbufs;
    Py_ssize_t shape[2];
    Py_ssize_t strides[2];
} mask_bufinfo;

static int
pgMask_GetBuffer(pgMaskObject *self, Py_buffer *view, int flags)
{
    bitmask_t *m = self->mask;
    mask_bufinfo *bufinfo = (mask_bufinfo *)self->bufdata;

    if (bufinfo == NULL) {
        bufinfo = PyMem_RawMalloc(sizeof(mask_bufinfo));
        if (bufinfo == NULL) {
            PyErr_NoMemory();
            return -1;
        }
        bufinfo->numbufs = 1;

        bufinfo->shape[0] = (m->w - 1) / BITMASK_W_LEN + 1;
        bufinfo->shape[1] = m->h;

        bufinfo->strides[0] = m->h * sizeof(BITMASK_W);
        bufinfo->strides[1] = sizeof(BITMASK_W);

        self->bufdata = bufinfo;
    }
    else {
        bufinfo->numbufs++;
    }

    view->buf = m->bits;
    view->len = m->h * ((m->w - 1) / BITMASK_W_LEN + 1) * sizeof(BITMASK_W);
    view->readonly = 0;
    view->itemsize = sizeof(BITMASK_W);
    view->ndim = 2;
    view->internal = bufinfo;
    view->shape = (flags & PyBUF_ND) ? bufinfo->shape : NULL;
    view->strides = (flags & PyBUF_STRIDES) ? bufinfo->strides : NULL;
    if (flags & PyBUF_FORMAT) {
        view->format = "L"; /* L = unsigned long */
    }
    else {
        view->format = NULL;
    }
    view->suboffsets = NULL;

    Py_INCREF(self);
    view->obj = (PyObject *)self;

    return 0;
}

static void
pgMask_ReleaseBuffer(pgMaskObject *self, Py_buffer *view)
{
    mask_bufinfo *bufinfo = (mask_bufinfo *)view->internal;

    bufinfo->numbufs--;
    if (bufinfo->numbufs == 0) {
        PyMem_RawFree(bufinfo);
        self->bufdata = NULL;
    }
}

static PyBufferProcs pgMask_BufferProcs = {
    (getbufferproc)pgMask_GetBuffer, (releasebufferproc)pgMask_ReleaseBuffer};

static PyTypeObject pgMask_Type = {
    PyVarObject_HEAD_INIT(NULL, 0).tp_name = "pygame.mask.Mask",
    .tp_basicsize = sizeof(pgMaskObject),
    .tp_dealloc = mask_dealloc,
    .tp_repr = (reprfunc)mask_repr,
    .tp_as_buffer = &pgMask_BufferProcs,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_doc = DOC_PYGAMEMASKMASK,
    .tp_methods = mask_methods,
    .tp_init = mask_init,
    .tp_new = mask_new,
};

/*mask module methods*/
static PyMethodDef _mask_methods[] = {
    {"from_surface", (PyCFunction)mask_from_surface,
     METH_VARARGS | METH_KEYWORDS, DOC_PYGAMEMASKFROMSURFACE},
    {"from_threshold", (PyCFunction)mask_from_threshold,
     METH_VARARGS | METH_KEYWORDS, DOC_PYGAMEMASKFROMTHRESHOLD},
    {NULL, NULL, 0, NULL}};

MODINIT_DEFINE(mask)
{
    PyObject *module, *apiobj;
    static void *c_api[PYGAMEAPI_MASK_NUMSLOTS];

    static struct PyModuleDef _module = {PyModuleDef_HEAD_INIT,
                                         "mask",
                                         DOC_PYGAMEMASK,
                                         -1,
                                         _mask_methods,
                                         NULL,
                                         NULL,
                                         NULL,
                                         NULL};

    /* imported needed apis; Do this first so if there is an error
       the module is not loaded.
    */
    import_pygame_base();
    if (PyErr_Occurred()) {
        return NULL;
    }
    import_pygame_color();
    if (PyErr_Occurred()) {
        return NULL;
    }
    import_pygame_surface();
    if (PyErr_Occurred()) {
        return NULL;
    }
    import_pygame_rect();
    if (PyErr_Occurred()) {
        return NULL;
    }

    /* create the mask type */
    if (PyType_Ready(&pgMask_Type) < 0) {
        return NULL;
    }

    /* create the module */
    module = PyModule_Create(&_module);
    if (module == NULL) {
        return NULL;
    }
    Py_INCREF(&pgMask_Type);
    if (PyModule_AddObject(module, "MaskType", (PyObject *)&pgMask_Type)) {
        Py_DECREF(&pgMask_Type);
        Py_DECREF(module);
        return NULL;
    }

    Py_INCREF(&pgMask_Type);
    if (PyModule_AddObject(module, "Mask", (PyObject *)&pgMask_Type)) {
        Py_DECREF(&pgMask_Type);
        Py_DECREF(module);
        return NULL;
    }

    /* export the c api */
    c_api[0] = &pgMask_Type;
    apiobj = encapsulate_api(c_api, "mask");
    if (PyModule_AddObject(module, PYGAMEAPI_LOCAL_ENTRY, apiobj)) {
        Py_XDECREF(apiobj);
        Py_DECREF(module);
        return NULL;
    }
    return module;
}