summaryrefslogtreecommitdiff
path: root/src/changes/chess.h
blob: e86911a194a5479f9191f1f3bbd588e177391b6f (plain)
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
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
/**

Copyright (c) Scott Gasch

Module Name:

    chess.h

Abstract:

Author:

    Scott Gasch ([email protected]) 7 Apr 2004

Revision History:

    $Id: chess.h 350 2008-06-28 03:12:34Z scott $

**/

#ifndef CHESS_
#define CHESS_

#include "compiler.h"

//
// Datatype wrappers
//
#define MIN_CHAR                   (0x80)
#define MAX_CHAR                   (0x7f)
typedef char                       CHAR;

#define MIN_BYTE                   (0x00)
#define MAX_BYTE                   (0xff)
typedef unsigned char              BYTE;

#define MIN_UCHAR                  (0x00)
#define MAX_UCHAR                  (0xff)
typedef unsigned char              UCHAR;
#define CAN_FIT_IN_UCHAR(x)        ((x) <= MAX_UCHAR)

#define MIN_SHORT                  (0x8000)
#define MAX_SHORT                  (0x7fff)
typedef signed short               SHORT;

#define MIN_USHORT                 (0x0000)
#define MAX_USHORT                 (0xffff)
typedef unsigned short             USHORT;
#define CAN_FIT_IN_USHORT(x)       ((x) <= MAX_USHORT)

#define MIN_WORD                   (0x0000)
#define MAX_WORD                   (0xffff)
typedef unsigned short             WORD;

#define MIN_INT                    (0x80000000)
#define MAX_INT                    (0x7fffffff)
typedef signed int                 INT;

#define MIN_DWORD                  (0x00000000)
#define MAX_DWORD                  (0xffffffff)
typedef unsigned int               DWORD;

#define MIN_UINT                   (0x00000000)
#define MAX_UINT                   (0xffffffff)
typedef unsigned int               UINT;

#define MIN_ULONG                  (0x00000000)
#define MAX_ULONG                  (0xffffffff)
typedef unsigned int               ULONG;

#define MIN_INT64                  (0x8000000000000000)
#define MAX_INT64                  (0x7fffffffffffffff)
typedef signed COMPILER_LONGLONG   INT64;

#define MIN_UINT64                 (0x0000000000000000)
#define MAX_UINT64                 (0xffffffffffffffff)
typedef unsigned COMPILER_LONGLONG UINT64;

#define MIN_BITBOARD               (0x0000000000000000)
#define MAX_BITBOARD               (0xffffffffffffffff)
typedef UINT64                     BITBOARD;

#define MIN_BITV                   MIN_UINT
#define MAX_BITV                   MAX_UINT
typedef unsigned int               BITV;

#define MIN_FLAG                   MIN_UINT
#define MAX_FLAG                   MAX_UINT
typedef unsigned int               FLAG;
#define IS_VALID_FLAG(x)           (((x) == TRUE) || ((x) == FALSE))

typedef unsigned int               COOR;
typedef unsigned int               PIECE;
typedef signed int                 SCORE;

#define BIT1                              (0x1)
#define BIT2                              (0x2)
#define BIT3                              (0x4)
#define BIT4                              (0x8)
#define BIT5                             (0x10)
#define BIT6                             (0x20)
#define BIT7                             (0x40)
#define BIT8                             (0x80)
#define BIT9                            (0x100)
#define BIT10                           (0x200)
#define BIT11                           (0x400)
#define BIT12                           (0x800)
#define BIT13                          (0x1000)
#define BIT14                          (0x2000)
#define BIT15                          (0x4000)
#define BIT16                          (0x8000)
#define BIT17                         (0x10000)
#define BIT18                         (0x20000)
#define BIT19                         (0x40000)
#define BIT20                         (0x80000)
#define BIT21                        (0x100000)
#define BIT22                        (0x200000)
#define BIT23                        (0x400000)
#define BIT24                        (0x800000)
#define BIT25                       (0x1000000)
#define BIT26                       (0x2000000)
#define BIT27                       (0x4000000)
#define BIT28                       (0x8000000)
#define BIT29                      (0x10000000)
#define BIT30                      (0x20000000)
#define BIT31                      (0x40000000)
#define BIT32                      (0x80000000)

typedef struct _DLIST_ENTRY
{
    struct _DLIST_ENTRY *pFlink;
    struct _DLIST_ENTRY *pBlink;
} DLIST_ENTRY;

//
// Constants
//
#define YES                        (1)
#define NO                         (0)
#ifndef TRUE
#define TRUE                       (YES)
#endif
#ifndef FALSE
#define FALSE                      (NO)
#endif

//
// Calculate the length of an array (i.e. number of elements)
//
#define ARRAY_LENGTH(x)            (sizeof(x) / sizeof((x)[0]))
#define COMMAND(x) \
    void (x)(CHAR *szInput, ULONG argc, CHAR *argv[], POSITION *pos)
#define MB (1024 * 1024)

//
// Calculate the address of the base of the structure given its type, and an
// address of a field within the structure.
//
#ifndef OFFSET_OF
#define OFFSET_OF(field, type) \
    (ULONG)(&((type *)0)->field)
#endif
#ifndef CONTAINING_STRUCT
#define CONTAINING_STRUCT(address, type, field) \
    ((type *)((BYTE *)(address) - (BYTE *)(OFFSET_OF(field, type))))
#endif

#define WHITE                      (1)
#define BLACK                      (0)
#define BAD_COLOR                  (2)
#define IS_VALID_COLOR(x)          (((x) == WHITE) || ((x) == BLACK))
#define FOREACH_COLOR(x)           for((x) = BLACK; (x) < BAD_COLOR; (x)++)
#define RANDOM_COLOR               (rand() & 1)
#define FLIP(color)                ((color) ^ 1)
#define COLOR_NAME(color)          (((color) == WHITE) ? "white" : "black")

#define MAX_MOVES_PER_PLY          (218)
#define MAX_PLY_PER_SEARCH         (64)
#define MAX_MOVES_PER_GAME         (1024)
#define SMALL_STRING_LEN_CHAR      (256)
#define MEDIUM_STRING_LEN_CHAR     (8192)
#define BIG_STRING_LEN_CHAR        (16384)

#define QUARTER_PLY                16
#define HALF_PLY                   32
#define THREE_QUARTERS_PLY         48
#define ONE_PLY                    64
#define TWO_PLY                    128
#define THREE_PLY                  192
#define FOUR_PLY                   256
#define MAX_DEPTH_PER_SEARCH       (MAX_PLY_PER_SEARCH * ONE_PLY)

#define IS_VALID_DEPTH(x)          (((x) >= 0) && \
                                   ((x) <= MAX_DEPTH_PER_SEARCH) && \
                                   (((x) & 0xfffff00f) == 0))

#define INFINITY                   (MAX_SHORT)
#define INVALID_SCORE              (INFINITY + 1)
#define IS_VALID_SCORE(x)          (((x) >= -INFINITY) && \
                                    ((x) <= +INFINITY))
#define NMATE                      (+INFINITY - 200)
#define MATED_SCORE(ply)           (-INFINITY + (ply))

#define IS_A_POWER_OF_2(x)         (((x) & (x - 1)) == 0)
//
// Program version number
//
#define VERSION                    "1.00"
#define REVISION                   "$Id: chess.h 350 2008-06-28 03:12:34Z scott $\n"

//
// Function decorators
//
#define IN
#define OUT
#define INOUT
#define UNUSED
#define NOTHING

// ----------------------------------------------------------------------
//
// PIECE:
//
// a piece (4 bits) = type (3 bits) + color (1 bit)
//
//  3   1 0
//  . . . .
// |     | |
//  type  C
//
#define KING                       (6)        // 110X
#define QUEEN                      (5)        // 101X
#define ROOK                       (4)        // 100X
#define BISHOP                     (3)        // 011X
#define KNIGHT                     (2)        // 010X
#define PAWN                       (1)        // 001X
#define EMPTY                      (0)        // 000X

// (WHATEVER << 1)
#define BLACK_PAWN                 (2)        // 0010
#define BLACK_KNIGHT               (4)        // 0100
#define BLACK_BISHOP               (6)        // 0110
#define BLACK_ROOK                 (8)        // 1000
#define BLACK_QUEEN                (10)       // 1010
#define BLACK_KING                 (12)       // 1100

// (WHATEVER << 1) | WHITE
#define WHITE_PAWN                 (3)        // 0011
#define WHITE_KNIGHT               (5)        // 0101
#define WHITE_BISHOP               (7)        // 0111
#define WHITE_ROOK                 (9)        // 1001
#define WHITE_QUEEN                (11)       // 1011
#define WHITE_KING                 (13)       // 1101

#define PIECE_TYPE(p)              ((p) >> 1)
#define PIECE_COLOR(p)             ((p) & WHITE)
#define RANDOM_PIECE               (rand() % 12) + 2;
#define IS_PAWN(p)                 (((p) & 0xE) == BLACK_PAWN)
#define IS_KNIGHT(p)               (((p) & 0xE) == BLACK_KNIGHT)
#define IS_BISHOP(p)               (((p) & 0xE) == BLACK_BISHOP)
#define IS_ROOK(p)                 (((p) & 0xE) == BLACK_ROOK)
#define IS_QUEEN(p)                (((p) & 0xE) == BLACK_QUEEN)
#define IS_KING(p)                 (((p) & 0xE) == BLACK_KING)
#define IS_KNIGHT_OR_KING(p)       (((p) & 0x6) == 0x4)
#define IS_VALID_PIECE(p)          ((PIECE_TYPE((p)) >= PAWN) && \
                                    (PIECE_TYPE((p)) <= KING))
#define IS_WHITE_PIECE(p)          ((p) & WHITE)
#define IS_BLACK_PIECE(p)          (!IS_WHITE(p))
#define OPPOSITE_COLORS(p, q)      (((p) ^ (q)) & WHITE)
#define SAME_COLOR(p,q)            (!OPPOSITE_COLORS(p, q))
#define GET_COLOR(p)               ((p) & WHITE)

// ----------------------------------------------------------------------
//
// a coordinate (8 bits) = rank + file (0x88)
//
//  7     4 3     0
//  . . . . . . . .
// |       |       |
//   rank     file
//     |        |
//     |        +--- 0-7 = file A thru file H
//     |
//     +------------ 0-7 = rank 1 thru rank 8
//
// given a coordinate, C, if C & 0x88 then it is illegal (off board)
//
//
//     0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07
//    +---------------------------------------+
//  8 | 00 |:01:| 02 |:03:| 04 |:05:| 06 |:07:| 0x00
//  7 |:10:| 11 |:12:| 13 |:14:| 15 |:16:| 17 | 0x10
//  6 | 20 |:21:| 22 |:23:| 24 |:25:| 26 |:27:| 0x20
//  5 |:30:| 31 |:32:| 33 |:34:| 35 |:36:| 37 | 0x30
//  4 | 40 |:41:| 42 |:43:| 44 |:45:| 46 |:47:| 0x40
//  3 |:50:| 51 |:52:| 53 |:54:| 55 |:56:| 57 | 0x50
//  2 | 60 |:61:| 62 |:63:| 64 |:65:| 66 |:67:| 0x60
//  1 |:70:| 71 |:72:| 73 |:74:| 75 |:76:| 77 | 0x70
//    +---------------------------------------+
//       A    B    C    D    E    F    G    H
//
#define A                          (0)
#define B                          (1)
#define C                          (2)
#define D                          (3)
#define E                          (4)
#define F                          (5)
#define G                          (6)
#define H                          (7)

#define A8                         (0x00)
#define B8                         (0x01)
#define C8                         (0x02)
#define D8                         (0x03)
#define E8                         (0x04)
#define F8                         (0x05)
#define G8                         (0x06)
#define H8                         (0x07)

#define A7                         (0x10)
#define B7                         (0x11)
#define C7                         (0x12)
#define D7                         (0x13)
#define E7                         (0x14)
#define F7                         (0x15)
#define G7                         (0x16)
#define H7                         (0x17)

#define A6                         (0x20)
#define B6                         (0x21)
#define C6                         (0x22)
#define D6                         (0x23)
#define E6                         (0x24)
#define F6                         (0x25)
#define G6                         (0x26)
#define H6                         (0x27)

#define A5                         (0x30)
#define B5                         (0x31)
#define C5                         (0x32)
#define D5                         (0x33)
#define E5                         (0x34)
#define F5                         (0x35)
#define G5                         (0x36)
#define H5                         (0x37)

#define A4                         (0x40)
#define B4                         (0x41)
#define C4                         (0x42)
#define D4                         (0x43)
#define E4                         (0x44)
#define F4                         (0x45)
#define G4                         (0x46)
#define H4                         (0x47)

#define A3                         (0x50)
#define B3                         (0x51)
#define C3                         (0x52)
#define D3                         (0x53)
#define E3                         (0x54)
#define F3                         (0x55)
#define G3                         (0x56)
#define H3                         (0x57)

#define A2                         (0x60)
#define B2                         (0x61)
#define C2                         (0x62)
#define D2                         (0x63)
#define E2                         (0x64)
#define F2                         (0x65)
#define G2                         (0x66)
#define H2                         (0x67)

#define A1                         (0x70)
#define B1                         (0x71)
#define C1                         (0x72)
#define D1                         (0x73)
#define E1                         (0x74)
#define F1                         (0x75)
#define G1                         (0x76)
#define H1                         (0x77)

// TODO: if use this anywhere that matters, consider double loop
// and unrolling the inside loop to prevent the multiple
// continue for invalid squares
#define FOREACH_SQUARE(x)          for((x) = (A8); (x) <= (H1); (x)++)

#define IS_ON_BOARD(c)             (!((c) & 0x88))
#define RANDOM_COOR                (rand() & 0x77)
#define FILE_RANK_TO_COOR(f, r)    (((8 - (r)) << 4) | (f))
#define RANK(c)                    (8 - ((c) >> 4))
#define RANK1(c)                   (((c) & 0xF0) == 0x70)
#define RANK2(c)                   (((c) & 0xF0) == 0x60)
#define RANK3(c)                   (((c) & 0xF0) == 0x50)
#define RANK4(c)                   (((c) & 0xF0) == 0x40)
#define RANK5(c)                   (((c) & 0xF0) == 0x30)
#define RANK6(c)                   (((c) & 0xF0) == 0x20)
#define RANK7(c)                   (((c) & 0xF0) == 0x10)
#define RANK8(c)                   (((c) & 0xF0) == 0x00)
#define FILE(c)                    ((c) & 0x0F)
#define FILEA(c)                   (((c) & 0x0F) == 0x00)
#define FILEB(c)                   (((c) & 0x0F) == 0x01)
#define FILEC(c)                   (((c) & 0x0F) == 0x02)
#define FILED(c)                   (((c) & 0x0F) == 0x03)
#define FILEE(c)                   (((c) & 0x0F) == 0x04)
#define FILEF(c)                   (((c) & 0x0F) == 0x05)
#define FILEG(c)                   (((c) & 0x0F) == 0x06)
#define FILEH(c)                   (((c) & 0x0F) == 0x07)
#define IS_WHITE_SQUARE_FR(f, r)   (((f) + (r) - 1) & 1)
#define IS_WHITE_SQUARE_COOR(c)    (IS_WHITE_SQUARE_FR(FILE(c), RANK(c)))
#define VALID_EP_SQUARE(c)         (((c) == ILLEGAL_COOR) || ((c) == 0) || \
                                    (RANK3(c)) || \
                                    (RANK6(c)))

// ----------------------------------------------------------------------
//
// a move (4 bytes) = from/to, moved, captured, promoted and special
//
//  31           24 23           16 15   12 11    8 7     4 3     0
//  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// |     from      |       to      | moved | capt  | prom  | flags |
//         |               |          |       |       |
//         |               |          |       |       |
//         |               |          |       |       |
//         |               |          +-------+-------+-- type and
//         |               |                              color of
//         |               |                              piece moved
//         |               |                              captured and
//         |               |                              promote targ
//         +---------------+-- board location where
//                             move begins and ends
//
//
// Special flag asserted on special move types:
//
// if (special)
// {
//    if (moved == PAWN)
//    {
//       if (promotion)
//       {
//          move is a promote (w/ or w/o capture)
//       }
//       else if (capture)
//       {
//          move is an en passant catpure
//       }
//       else
//       {
//          move is a double jump
//       }
//    }
//    else if (moved == KING)
//    {
//       move is a castle (long or short)
//    }
//    else
//    {
//       invalid use of special flag
//    }
// }
//
typedef union _MOVE
{
    ULONG uMove;
    struct
    {
        UCHAR cFrom        : 8;
        UCHAR cTo          : 8;
        UCHAR pMoved       : 4;
        UCHAR pCaptured    : 4;
        UCHAR pPromoted    : 4;
        UCHAR bvFlags      : 4;
    };
} MOVE;

#define IS_SAME_MOVE(a, b) \
    (((a).uMove & 0x0FFFFFFF) == (((b).uMove & 0x0FFFFFFF)))

#define MAKE_MOVE(from,to,piece,cap,prom,flags) \
    (((ULONG)(from)) | \
     ((ULONG)(to) << 8) | \
     ((ULONG)(piece) << 16) | \
     ((ULONG)(cap) << 20) | \
     ((ULONG)(prom) << 24) | \
     ((ULONG)(flags) << 28))

#define MAKE_MOVE_WITH_NO_PROM_OR_FLAGS(from,to,piece,cap) \
    (((ULONG)(from)) | \
     ((ULONG)(to) << 8) | \
     ((ULONG)(piece) << 16) | \
     ((ULONG)(cap) << 20))

//
// Move flag values:
//
#define MOVE_FLAG_SPECIAL          (1)        // en pass, prom, castle, double
#define IS_SPECIAL_MOVE(mv)         \
    ((mv).uMove & 0x10000000)

#define IS_CASTLE(mv)               \
    (IS_SPECIAL_MOVE(mv) && IS_KING((mv).pMoved))

#ifdef DEBUG
#define IS_PROMOTION(mv)            \
    (IS_SPECIAL_MOVE(mv) && ((mv).pPromoted))
#else
#define IS_PROMOTION(mv)            \
    ((mv).pPromoted)
#endif

#define IS_CAPTURE_OR_PROMOTION(mv) \
    ((mv).uMove & 0x0FF00000)

#define IS_ENPASSANT(mv)            \
    (IS_SPECIAL_MOVE(mv) && (mv.pCaptured) && !IS_PROMOTION(mv))

#define IS_DOUBLE_JUMP(mv)          \
    (IS_SPECIAL_MOVE(mv) && !IS_CAPTURE_OR_PROMOTION(mv))

#define MOVE_FLAG_KILLERMATE       (2)        // killer mate
#define IS_KILLERMATE_MOVE(mv)     ((mv).uMove & 0x20000000)

#define MOVE_FLAG_ESCAPING_CHECK   (4)        // escaping check
#define IS_ESCAPING_CHECK(mv)      ((mv).uMove & 0x40000000)

#define MOVE_FLAG_CHECKING         (8)        // checking move
#define IS_CHECKING_MOVE(mv)       ((mv).uMove & 0x80000000)

// ----------------------------------------------------------------------
//
// Move list
//
#define MAX_MOVE_LIST              (MAX_MOVES_PER_GAME + MAX_PLY_PER_SEARCH)

// ----------------------------------------------------------------------

#pragma pack(1)
typedef union _ATTACK_BITV
{
    ULONG uWholeThing;
    struct
    {
        union
        {
            UCHAR uSmall;
            struct
            {
                UCHAR uNumAttacks : 3;            // 0..2
                UCHAR uKing : 1;                  // 4..7
                UCHAR uQueen : 1;
                UCHAR uRook : 1;
                UCHAR uMinor : 1;
                UCHAR uPawn : 1;
            } small;
        };

        // --------------------
        union
        {
            USHORT uBig;
            struct
            {
                USHORT uKing : 1;                  // 8..23
                USHORT uQueens : 4;
                USHORT uRooks : 4;
                USHORT uMinors : 4;
                USHORT uPawns : 2;
                USHORT uUnusedFlag1 : 1;
            } big;
        };

        // -------------------
        union
        {
            UCHAR uXray;
            struct
            {
                UCHAR uNumXrays : 3;
                UCHAR uUnusedFlag2 : 1;
                UCHAR uQueen : 1;                 // 24..28
                UCHAR uRook : 1;
                UCHAR uBishop : 1;
                UCHAR uUnusedFlag3 : 1;
            } xray;
        };
    };
}
ATTACK_BITV;

#define UNSAFE_FOR_MINOR(x) ((ULONG)((x).uWholeThing) & 0x00000080UL)
#define UNSAFE_FOR_ROOK(x)  ((ULONG)((x).uWholeThing) & 0x000000C0UL)
#define UNSAFE_FOR_QUEEN(x) ((ULONG)((x).uWholeThing) & 0x000000E0UL)

#define PAWN_BIT       0x00000080UL
#define MINOR_BIT      0x00000040UL
#define MINOR_XRAY_BIT 0x40000000UL
#define ROOK_BIT       0x00000020UL
#define ROOK_XRAY_BIT  0x20000000UL
#define QUEEN_BIT      0x00000010UL
#define QUEEN_XRAY_BIT 0x10000000UL

#define INVALID_PIECE_INDEX (17)
#define IS_VALID_PIECE_INDEX(x) ((x) < INVALID_PIECE_INDEX)

typedef union _SQUARE
{
    struct
    {
        PIECE pPiece;
        ULONG uIndex;
    };
    ATTACK_BITV bvAttacks[2];
}
SQUARE;
#pragma pack()

//
// POSITION
//
typedef struct _POSITION
{
    SQUARE rgSquare[128];                  // where the pieces are,
                                           // also, the attack table
    UINT64 u64NonPawnSig;                  // hash signature
    UINT64 u64PawnSig;                     // pawn hash signature
    ULONG uToMove;                         // whose turn?
    ULONG uFifty;                          // 50 moves w/o progress = draw
    FLAG fCastled[2];                      // record when sides have castled
    BITV bvCastleInfo;                     // who can castle how?
    COOR cEpSquare;                        // en-passant capture square

    COOR cPawns[2][8];                     // location of pawns on the board
    ULONG uPawnMaterial[2];                // pawn material of each side
    ULONG uPawnCount[2];                   // number of pawns for each side

    COOR cNonPawns[2][16];                 // location of pieces on the board
    ULONG uNonPawnMaterial[2];             // piece material of each side
    ULONG uNonPawnCount[2][8];             // number of non-pawns / type
                                           // 0 and 1 are the sum,
                                           // 2..6 are per PIECE_TYPE

    ULONG uWhiteSqBishopCount[2];          // num bishops on white squares
    SCORE iMaterialBalance[2];             // material balance

    // temporary storage space for use in eval
    COOR cTrapped[2];
    ULONG uArmyScaler[2];
    ULONG uClosedScaler;
    SCORE iScore[2];
    SCORE iReducedMaterialDownScaler[2];
    SCORE iTempScore;
    ULONG uMinMobility[2];
    COOR cPiece;
    ULONG uMinorsAtHome[2];
    BITBOARD bb;
    ULONG uPiecesPointingAtKing[2];
}
POSITION;

//
// Castling permission bitvector flags.
//
#define CASTLE_WHITE_SHORT                (1)
#define CASTLE_WHITE_LONG                 (2)
#define WHITE_CAN_CASTLE                  \
    (CASTLE_WHITE_SHORT | CASTLE_WHITE_LONG)
#define CASTLE_BLACK_SHORT                (4)
#define CASTLE_BLACK_LONG                 (8)
#define BLACK_CAN_CASTLE                  \
    (CASTLE_BLACK_SHORT | CASTLE_BLACK_LONG)
#define CASTLE_NONE_POSSIBLE              (0)
#define CASTLE_ALL_POSSIBLE               \
    (WHITE_CAN_CASTLE | BLACK_CAN_CASTLE)

// ----------------------------------------------------------------------
//
// Move stack
//
#define MAX_MOVE_STACK             (MAX_PLY_PER_SEARCH * \
                                    MAX_MOVES_PER_PLY)

//
// Main part of the move stack, triads of moves, their values and flags
// that denote where the values came from
//
#define MVF_MOVE_SEARCHED    (1)
#define MVF_EXTEND_MOVE      (2)
#define MVF_REDUCE_MOVE      (4)
#define MVF_PRUNE_SUBTREE    (8)

typedef struct _MOVE_STACK_MOVE_VALUE_FLAGS
{
    SCORE iValue;
    MOVE mv;
    BITV bvFlags;
}
MOVE_STACK_MOVE_VALUE_FLAGS;

typedef struct _KEY_POINTER
{
    int iPointer;
    ULONG uKey;
}
KEY_POINTER;

typedef union _GENERATOR_FLAGS 
{
    struct {
        UCHAR uMoveCount;
        UCHAR uKingMoveCount;
        UCHAR uCheckingPieces;
        UCHAR uUnused;
    };
    ULONG uAllGenFlags;
}
GENERATOR_FLAGS;

//
// A move stack
//
typedef struct _MOVE_STACK
{
#ifdef DEBUG
    POSITION board[MAX_PLY_PER_SEARCH];
#endif
    //
    // Unblocked squares map, used for check detection
    //
    ULONG uUnblockedKeyValue[MAX_PLY_PER_SEARCH];
    KEY_POINTER sUnblocked[MAX_PLY_PER_SEARCH][128];

    //
    // The main move list, a long series of moves, their values and some
    // flag bits to tell search what the values are based upon.
    //
    MOVE_STACK_MOVE_VALUE_FLAGS mvf[MAX_MOVE_STACK];

    //
    // uBegin[ply] and uEnd[ply] specify the start and end of moves gen-
    // erated for a position at ply distance from the root.
    //
    ULONG uPly;
    ULONG uBegin[MAX_PLY_PER_SEARCH];
    ULONG uEnd[MAX_PLY_PER_SEARCH];
    MOVE mvHash[MAX_PLY_PER_SEARCH];
    GENERATOR_FLAGS sGenFlags[MAX_PLY_PER_SEARCH];
}
MOVE_STACK;

#define GENERATE_NO_MOVES                              \
    ctx->sMoveStack.uEnd[ctx->uPly] =                  \
        ctx->sMoveStack.uBegin[ctx->uPly] + 1;         \
    ctx->sMoveStack.uBegin[ctx->uPly + 1] =            \
        ctx->sMoveStack.uEnd[ctx->uPly]

#define GENERATE_ALL_MOVES             (1)
#define GENERATE_ESCAPES               (2)
#define GENERATE_CAPTURES_PROMS_CHECKS (3)
#define GENERATE_CAPTURES_PROMS        (4)
#define GENERATE_DONT_SCORE            (5)
#ifdef TEST
#define GENERATE_ALL_MOVES_CHECK_OK    (6)
#endif

#define MOVE_COUNT(ctx, x)             \
    (((ctx)->sMoveStack.uEnd[(x)]) - (ctx)->sMoveStack.uBegin[(x)])
#define ONE_LEGAL_MOVE(ctx, x) \
    (MOVE_COUNT(ctx, x) == 1)
#define NUM_KING_MOVES(ctx, x) \
    ((ctx)->sMoveStack.sGenFlags[(x)].uKingMoveCount)
#define NUM_CHECKING_PIECES(ctx, x) \
    ((ctx)->sMoveStack.sGenFlags[(x)].uCheckingPieces)


// ----------------------------------------------------------------------
//
// Accumulators
//
typedef struct _COUNTERS
{
    struct
    {
        UINT64 u64Probes;
        UINT64 u64OverallHits;
        UINT64 u64UsefulHits;
        UINT64 u64UpperBoundHits;
        UINT64 u64LowerBoundHits;
        UINT64 u64ExactScoreHits;
    }
    hash;

    struct
    {
        UINT64 u64Probes;
        UINT64 u64Hits;
    }
    pawnhash;

    struct
    {
        UINT64 u64TotalNodeCount;
        UINT64 u64QNodeCount;
        UINT64 u64LeafCount;
        UINT64 u64TerminalPositionCount;
        UINT64 u64BetaCutoffs;
        UINT64 u64BetaCutoffsOnFirstMove;
        UINT64 u64NullMoves;
        UINT64 u64NullMoveSuccess;
#ifdef TEST_NULL
        UINT64 u64QuickNullSuccess;
        UINT64 u64QuickNullDeferredSuccess;
        UINT64 u64QuickNullFailures;
        UINT64 u64AvoidNullSuccess;
        UINT64 u64AvoidNullFailures;
#endif
        UINT64 u64EvalHashHits;
        UINT64 u64LazyEvals;
        UINT64 u64FullEvals;
        UINT64 u64CyclesInEval;
    }
    tree;

    struct
    {
        ULONG uNumSplits;
        ULONG uNumSplitsTerminated;
    }
    parallel;

    struct
    {
        ULONG uPawnPush;
        ULONG uCheck;
        ULONG uMateThreat;
        ULONG uRecapture;
        ULONG uOneLegalMove;
        ULONG uNoLegalKingMoves;
        ULONG uMultiCheck;
        ULONG uSingularMove;
        ULONG uZugzwang;
        ULONG uSingularReplyToCheck;
        ULONG uEndgame;
        ULONG uBotvinnikMarkoff;
        ULONG uQExtend;
    }
    extension;

    struct
    {
        ULONG uProbes;
        ULONG uHits;
    }
    egtb;
}
COUNTERS;

typedef struct _CUMULATIVE_SEARCH_FLAGS
{
    // search
    ULONG uNumChecks[2];                      // not used
    FLAG fInSuspiciousBranch;                 // not used
    FLAG fInReducedDepthBranch;               // not used
    FLAG fAvoidNullmove;                      // restore
    FLAG fVerifyNullmove;                     // restore

    // qsearch
    ULONG uQsearchDepth;                      // restore
    ULONG uQsearchNodes;                      // incremental
    ULONG uQsearchCheckDepth;                 // restore
    FLAG fCouldStandPat[2];                   // restore
}
CUMULATIVE_SEARCH_FLAGS;

// ----------------------------------------------------------------------
//
// Searcher thread record
//
typedef struct _SPLIT_INFO
{
    // locks / counters
    volatile ULONG uLock;                     // lock for this split node
    volatile ULONG uNumThreadsHelping;        // num threads in this node
    volatile FLAG fTerminate;                 // signal helpers to terminate

    // moves in the split node
    ULONG uRemainingMoves;                    // num moves remaining to do
    ULONG uOnDeckMove;                        // next move to do
    ULONG uNumMoves;
    ULONG uAlreadyDone;
    MOVE_STACK_MOVE_VALUE_FLAGS
        mvf[MAX_MOVES_PER_PLY];               // the moves to search

    // input to the split node
    POSITION sRootPosition;                   // the root position
    MOVE mvPathToHere[MAX_PLY_PER_SEARCH];    // path from root to split
    MOVE mvLast;                              // last move before split
    ULONG uDepth;                             // remaining depth at split
    INT iPositionExtend;                      // positional extension
    SCORE iAlpha;                             // original alpha at split
    SCORE iBeta;                              // beta at split
    ULONG uSplitPositional;                   // pos->uPositional at split
    CUMULATIVE_SEARCH_FLAGS sSearchFlags;     // flags at split time

    // output from the split node
    MOVE mvBest;                              // the best move
    SCORE iBestScore;                         // it's score
    COUNTERS sCounters;                       // updated counters
    MOVE PV[MAX_PLY_PER_SEARCH];

#ifdef DEBUG
    ULONG uSplitPly;
    POSITION sSplitPosition;
#endif
}
SPLIT_INFO;

typedef struct _PLY_INFO
{
#ifdef DEBUG
    POSITION sPosition;
    SCORE iAlpha;
    SCORE iBeta;
#endif
    SCORE iEval;
    INT iExtensionAmount;
    FLAG fInCheck;
    FLAG fInQsearch;
    MOVE mv;
    MOVE mvBest;
    MOVE PV[MAX_PLY_PER_SEARCH];

    SCORE iKingScore[2];
    ULONG uMinMobility[2];
    UINT64 u64NonPawnSig;
    UINT64 u64PawnSig;
    UINT64 u64Sig;
    ULONG uFifty;
    FLAG fCastled[2];
    ULONG uTotalNonPawns;
    BITV bvCastleInfo;
    COOR cEpSquare;
}
PLY_INFO;

#define EVAL_HASH
#ifdef EVAL_HASH
#define EVAL_HASH_TABLE_SIZE (2097152) // 32Mb (per thread)
typedef struct _EVAL_HASH_ENTRY
{
    UINT64 u64Key;
    SCORE iEval;
    ULONG uPositional;
    COOR cTrapped[2];

} EVAL_HASH_ENTRY;
#endif

#define PAWN_HASH_TABLE_SIZE (131072) // 5.5Mb (per thread)
typedef struct _PAWN_HASH_ENTRY
{
    UINT64 u64Key;
    BITBOARD bbPawnLocations[2];
    BITBOARD bbPasserLocations[2];
    BITBOARD bbStationaryPawns[2];
    SHORT iScore[2];
    UCHAR uCountPerFile[2][10];
    UCHAR uNumRammedPawns;
    UCHAR uNumUnmovedPawns[2];
}
PAWN_HASH_ENTRY;

#define NUM_SPLIT_PTRS_IN_CONTEXT (8)

typedef struct _SEARCHER_THREAD_CONTEXT
{
    ULONG uPly;                               // its distance from root
    ULONG uPositional;                        // positional component of score
    POSITION sPosition;                       // the board
    MOVE_STACK sMoveStack;                    // the move stack
    CUMULATIVE_SEARCH_FLAGS sSearchFlags;
    PLY_INFO sPlyInfo[MAX_PLY_PER_SEARCH+1];
    MOVE mvKiller[MAX_PLY_PER_SEARCH][2];
    MOVE mvKillerEscapes[MAX_PLY_PER_SEARCH][2];
    MOVE mvNullmoveRefutations[MAX_PLY_PER_SEARCH];
    COUNTERS sCounters;
    ULONG uThreadNumber;
    SPLIT_INFO *pSplitInfo[NUM_SPLIT_PTRS_IN_CONTEXT];
    MOVE mvRootMove;
    SCORE iRootScore;
    ULONG uRootDepth;
    PAWN_HASH_ENTRY rgPawnHash[PAWN_HASH_TABLE_SIZE];
#ifdef EVAL_HASH
    EVAL_HASH_ENTRY rgEvalHash[EVAL_HASH_TABLE_SIZE];
#endif
    CHAR szLastPV[SMALL_STRING_LEN_CHAR];
}
SEARCHER_THREAD_CONTEXT;

//
// When I added the pawn hash table and eval hash tables to searcher
// thread contexts they became too heavy to just allocate on the fly
// for things like checking the legality of SAN moves or seeing if an
// opening book line leads to a draw.  This
// LIGHTWEIGHT_SEARCHER_CONTEXT structure can be cast into a full
// SEARCHER_THREAD_CONTEXT and passed safely into the Generate,
// MakeMove and UnMakeMove functions because they presently only
// need:
//
//     1. uPly
//     2. sPosition
//     3. sPlyInfo
//     4. sMoveStack
//
typedef struct _LIGHTWEIGHT_SEARCHER_CONTEXT
{
    ULONG uPly;
    ULONG uPositional;
    POSITION sPosition;
    MOVE_STACK sMoveStack;
    CUMULATIVE_SEARCH_FLAGS sSearchFlags;
    PLY_INFO sPlyInfo[MAX_PLY_PER_SEARCH+1];
}
LIGHTWEIGHT_SEARCHER_CONTEXT;

// ----------------------------------------------------------------------
//
// Global game options
//
typedef struct _GAME_OPTIONS
{
    ULONG uMyClock;
    ULONG uOpponentsClock;
    FLAG fGameIsRated;
    FLAG fOpponentIsComputer;
    ULONG uSecPerMove;
    ULONG uMaxDepth;
    UINT64 u64MaxNodeCount;
    FLAG fShouldPonder;
    FLAG fPondering;
    FLAG fThinking;
    FLAG fSuccessfulPonder;
    MOVE mvPonder;
    FLAG fShouldPost;
    FLAG fForceDrawWorthZero;
    ULONG uMyIncrement;
    ULONG uMovesPerTimePeriod;
    CHAR szAnalyzeProgressReport[SMALL_STRING_LEN_CHAR];
    FLAG fShouldAnnounceOpening;
    SCORE iLastEvalScore;
    UINT64 u64NodesSearched;
    CHAR szLogfile[SMALL_STRING_LEN_CHAR];
    CHAR szEGTBPath[SMALL_STRING_LEN_CHAR];
    CHAR szBookName[SMALL_STRING_LEN_CHAR];
    ULONG uNumProcessors;
    ULONG uNumHashTableEntries;
    FLAG fNoInputThread;
    FLAG fVerbosePosting;
    FLAG fRunningUnderXboard;
    FLAG fStatusLine;
    FLAG fFastScript;
    FLAG fShouldResign;

    enum
    {
        CLOCK_NORMAL               = 0,
        CLOCK_FIXED,
        CLOCK_INCREMENT,
        CLOCK_NONE
    }
    eClock;

    enum
    {
        GAME_UNKNOWN               = 0,
        GAME_BULLET,
        GAME_BLITZ,
        GAME_STANDARD
    }
    eGameType;

    enum
    {
        I_PLAY_WHITE               = 0,
        I_PLAY_BLACK,
        FORCE_MODE,
        EDIT_MODE,
        ANALYZE_MODE
    }
    ePlayMode;
}
GAME_OPTIONS;
extern GAME_OPTIONS g_Options;

// ----------------------------------------------------------------------
//
// Move timer
//

#define TIMER_SEARCHING_FIRST_MOVE       (0x1)
#define TIMER_SEARCHING_IMPORTANT_MOVE   (0x2)
#define TIMER_RESOLVING_ROOT_FL          (0x4)
#define TIMER_RESOLVING_ROOT_FH          (0x8)
#define TIMER_JUST_OUT_OF_BOOK           (0x10)
#define TIMER_CURRENT_OBVIOUS            (0x20)
#define TIMER_CURRENT_WONT_UNBLOCK       (0x40)
#define TIMER_ROOT_POSITION_CRITICAL     (0x80)
#define TIMER_MOVE_IMMEDIATELY           (0x100)
#define TIMER_MANY_ROOT_FLS              (0x200)
#define TIMER_STOPPING                   (0x400)
#define TIMER_SPLIT_FAILED               (0x800)

typedef struct _MOVE_TIMER
{
    double dStartTime;
    double dEndTime;
    double dSoftTimeLimit;
    double dHardTimeLimit;
    ULONG uNodeCheckMask;
    volatile BITV bvFlags;
}
MOVE_TIMER;

// ----------------------------------------------------------------------
//
// Special move tag literals
//
#define ILLEGALMOVE                ((ULONG)0x1DDD8888)

//
// useful macros
//
#ifdef DEBUG
void
_assert(CHAR *szFile, ULONG uLine);

#define ASSERT(x)                  if (x)    \
                                   { ; }     \
                                   else      \
                                   { _assert(__FILE__, __LINE__); }
#define VERIFY(x)                  ASSERT(x)
#else
#define ASSERT(x)                   ;
#define VERIFY(x)                  x;
#endif // DEBUG

#ifdef PERF_COUNTERS
#define INC(x)                     ((x) += 1)
#else
#define INC(x)
#endif

#define BREAKPOINT                 SystemDebugBreakpoint()

#define MIN(x, y)                  (((x) < (y)) ? (x) : (y))
#define MAX(x, y)                  (((x) > (y)) ? (x) : (y))

#ifdef _X86_
//
// Note: MAXU, MINU and ABS_DIFF require arguments with the high order
// bit CLEAR to work right.
//
// These are branchless constructs.  MAXU and MINU are equivalent to
// MIN and MAX (with the above restriction on inputs)
//
// MIN0 and MAX0 are equivalent to MAX(0, x) and MIN(0, x).  These
// macros have no restiction on argument type.
//
// ABS_DIFF is equivalent to abs(x - y).  Again, x and y must have
// their high-order bits CLEAR for this to work.
//
// Note: gcc generates code with cmovs so no need for MAXU/MINU on
// that compiler.
//
#define MINU(x, y)                 \
    (((((int)((x)-(y)))>>31) & ((x)-(y)))+(y))
#define MAXU(x, y)                 \
    (((((int)((x)-(y)))>>31) & ((y)-(x)))+(x))
#define MIN0(x)                    \
    ((x) & (((int)(x)) >> 31))
#define MAX0(x)                    \
    ((x) & ~(((int)(x)) >> 31))


#define ABS_DIFF(a, b)             \
    (((b)-(a)) - ((((b) - (a)) & (((int)((b) - (a))) >> 31) ) << 1))

#endif // _X86_

#ifndef MINU
#define MINU(x, y)                 (MIN((x), (y)))
#endif

#ifndef MAXU
#define MAXU(x, y)                 (MAX((x), (y)))
#endif

#ifndef MIN0
#define MIN0(x)                    (MIN((x), 0))
#endif

#ifndef MAX0
#define MAX0(x)                    (MAX((x), 0))
#endif

#ifndef ABS_DIFF
#define ABS_DIFF(a, b)             (abs((a) - (b)))
#endif

#define FILE_DISTANCE(a, b)        (ABS_DIFF(FILE((a)), FILE((b))))
#define RANK_DISTANCE(a, b)        (ABS_DIFF(((a) & 0xF0), ((b) & 0xF0)) >> 4)
#define REAL_DISTANCE(a, b)        (MAXU(FILE_DISTANCE((a), (b)), \
                                         RANK_DISTANCE((a), (b))))
#ifdef DEBUG
#define DISTANCE(a, b)             DistanceBetweenSquares((a), (b))
#else
#define DISTANCE(a, b)             g_pDistance[(a) - (b)]
#endif // DEBUG

#define    IS_EMPTY( square )      (!(square))
#define IS_OCCUPIED( square )      ((square))

#define IS_DEAD( listindex )       ((listindex) > 119)
#define IS_ALIVE( listindex )      ((listindex) <= 119)
#define ILLEGAL_COOR               (0x88)
#define EDGE_DISTANCE(c)           (MIN(MIN(abs(RANK(c) - 7), RANK(c)), \
                                        MIN(abs(FILE(c) - 7), FILE(c))))
#define NOT_ON_EDGE(c)             ((((c) & 0xF0) != 0x00) && \
                                       (((c) & 0xF0) != 0x70) && \
                                       (((c) & 0x0F) != 0x00) && \
                                       (((c) & 0x0F) != 0x07))
#define ON_EDGE(c)                 (RANK8(c) || \
                                    RANK1(c) || \
                                    FILEA(c) || \
                                    FILEH(c))
#define CORNER_DISTANCE(c)         (MAX(MIN((ULONG)abs(RANK(c) - 7), RANK(c)),\
                                        MIN((ULONG)abs(FILE(c) - 7), FILE(c))))
#define IN_CORNER(c)               (((c) == A8) || \
                                       ((c) == A1) || \
                                       ((c) == H8) || \
                                       ((c) == H1))
#define WHITE_CORNER_DISTANCE(c)   (MIN(DISTANCE((c), A8), \
                                        DISTANCE((c), H1)))
#define BLACK_CORNER_DISTANCE(c)   (MIN(DISTANCE((c), H8), \
                                        DISTANCE((c), A1)))
#define SYM_SQ(c)                  ((7 - (((c) & 0xF0) >> 4)) << 4) \
                                       | (7 - ((c) & 0x0F))
#define ARRAY_SIZE(a)              (sizeof((a)) / sizeof((a[0])))
#define MAKE_PSQT(a, b, c, d)      (((a) << 24) | ((b) << 16) | \
                                       ((c) << 8) | (d))
#define TO64(x)                    ((x) & 0x7) + ((0x7 - ((x)>>4)) << 3)
#define COOR_TO_BIT_NUMBER(c)      (((((c) & 0x70) >> 1) | ((c) & 0x7)))
#define SLOWCOOR_TO_BB(c)          (1ULL << COOR_TO_BIT_NUMBER(c))
#define COOR_TO_BB(c)              (BBSQUARE[COOR_TO_BIT_NUMBER(c)])
#define SLOW_BIT_NUMBER_TO_COOR(b) ((((b) / 8) << 4) + ((b) & 7))
#define BIT_NUMBER_TO_COOR(b)      ((((b) & 0xF8) << 1) | ((b) & 7))

#define BBRANK88 \
    SLOWCOOR_TO_BB(A8) | SLOWCOOR_TO_BB(B8) | SLOWCOOR_TO_BB(C8) | \
    SLOWCOOR_TO_BB(D8) | SLOWCOOR_TO_BB(E8) | SLOWCOOR_TO_BB(F8) | \
    SLOWCOOR_TO_BB(G8) | SLOWCOOR_TO_BB(H8)

#define BBRANK77 \
    SLOWCOOR_TO_BB(A7) | SLOWCOOR_TO_BB(B7) | SLOWCOOR_TO_BB(C7) | \
    SLOWCOOR_TO_BB(D7) | SLOWCOOR_TO_BB(E7) | SLOWCOOR_TO_BB(F7) | \
    SLOWCOOR_TO_BB(G7) | SLOWCOOR_TO_BB(H7)

#define BBRANK66 \
    SLOWCOOR_TO_BB(A6) | SLOWCOOR_TO_BB(B6) | SLOWCOOR_TO_BB(C6) | \
    SLOWCOOR_TO_BB(D6) | SLOWCOOR_TO_BB(E6) | SLOWCOOR_TO_BB(F6) | \
    SLOWCOOR_TO_BB(G6) | SLOWCOOR_TO_BB(H6)

#define BBRANK55 \
    SLOWCOOR_TO_BB(A5) | SLOWCOOR_TO_BB(B5) | SLOWCOOR_TO_BB(C5) | \
    SLOWCOOR_TO_BB(D5) | SLOWCOOR_TO_BB(E5) | SLOWCOOR_TO_BB(F5) | \
    SLOWCOOR_TO_BB(G5) | SLOWCOOR_TO_BB(H5)

#define BBRANK44 \
    SLOWCOOR_TO_BB(A4) | SLOWCOOR_TO_BB(B4) | SLOWCOOR_TO_BB(C4) | \
    SLOWCOOR_TO_BB(D4) | SLOWCOOR_TO_BB(E4) | SLOWCOOR_TO_BB(F4) | \
    SLOWCOOR_TO_BB(G4) | SLOWCOOR_TO_BB(H4)

#define BBRANK33 \
    SLOWCOOR_TO_BB(A3) | SLOWCOOR_TO_BB(B3) | SLOWCOOR_TO_BB(C3) | \
    SLOWCOOR_TO_BB(D3) | SLOWCOOR_TO_BB(E3) | SLOWCOOR_TO_BB(F3) | \
    SLOWCOOR_TO_BB(G3) | SLOWCOOR_TO_BB(H3)

#define BBRANK22 \
    SLOWCOOR_TO_BB(A2) | SLOWCOOR_TO_BB(B2) | SLOWCOOR_TO_BB(C2) | \
    SLOWCOOR_TO_BB(D2) | SLOWCOOR_TO_BB(E2) | SLOWCOOR_TO_BB(F2) | \
    SLOWCOOR_TO_BB(G2) | SLOWCOOR_TO_BB(H2)

#define BBRANK11 \
    SLOWCOOR_TO_BB(A1) | SLOWCOOR_TO_BB(B1) | SLOWCOOR_TO_BB(C1) | \
    SLOWCOOR_TO_BB(D1) | SLOWCOOR_TO_BB(E1) | SLOWCOOR_TO_BB(F1) | \
    SLOWCOOR_TO_BB(G1) | SLOWCOOR_TO_BB(H1)

#define BBFILEA \
    SLOWCOOR_TO_BB(A1) | SLOWCOOR_TO_BB(A2) | SLOWCOOR_TO_BB(A3) | \
    SLOWCOOR_TO_BB(A4) | SLOWCOOR_TO_BB(A5) | SLOWCOOR_TO_BB(A6) | \
    SLOWCOOR_TO_BB(A7) | SLOWCOOR_TO_BB(A8)

#define BBFILEB \
    SLOWCOOR_TO_BB(B1) | SLOWCOOR_TO_BB(B2) | SLOWCOOR_TO_BB(B3) | \
    SLOWCOOR_TO_BB(B4) | SLOWCOOR_TO_BB(B5) | SLOWCOOR_TO_BB(B6) | \
    SLOWCOOR_TO_BB(B7) | SLOWCOOR_TO_BB(B8)

#define BBFILEC \
    SLOWCOOR_TO_BB(C1) | SLOWCOOR_TO_BB(C2) | SLOWCOOR_TO_BB(C3) | \
    SLOWCOOR_TO_BB(C4) | SLOWCOOR_TO_BB(C5) | SLOWCOOR_TO_BB(C6) | \
    SLOWCOOR_TO_BB(C7) | SLOWCOOR_TO_BB(C8)

#define BBFILED \
    SLOWCOOR_TO_BB(D1) | SLOWCOOR_TO_BB(D2) | SLOWCOOR_TO_BB(D3) | \
    SLOWCOOR_TO_BB(D4) | SLOWCOOR_TO_BB(D5) | SLOWCOOR_TO_BB(D6) | \
    SLOWCOOR_TO_BB(D7) | SLOWCOOR_TO_BB(D8)

#define BBFILEE \
    SLOWCOOR_TO_BB(E1) | SLOWCOOR_TO_BB(E2) | SLOWCOOR_TO_BB(E3) | \
    SLOWCOOR_TO_BB(E4) | SLOWCOOR_TO_BB(E5) | SLOWCOOR_TO_BB(E6) | \
    SLOWCOOR_TO_BB(E7) | SLOWCOOR_TO_BB(E8)

#define BBFILEF \
    SLOWCOOR_TO_BB(F1) | SLOWCOOR_TO_BB(F2) | SLOWCOOR_TO_BB(F3) | \
    SLOWCOOR_TO_BB(F4) | SLOWCOOR_TO_BB(F5) | SLOWCOOR_TO_BB(F6) | \
    SLOWCOOR_TO_BB(F7) | SLOWCOOR_TO_BB(F8)

#define BBFILEG \
    SLOWCOOR_TO_BB(G1) | SLOWCOOR_TO_BB(G2) | SLOWCOOR_TO_BB(G3) | \
    SLOWCOOR_TO_BB(G4) | SLOWCOOR_TO_BB(G5) | SLOWCOOR_TO_BB(G6) | \
    SLOWCOOR_TO_BB(G7) | SLOWCOOR_TO_BB(G8)

#define BBFILEH \
    SLOWCOOR_TO_BB(H1) | SLOWCOOR_TO_BB(H2) | SLOWCOOR_TO_BB(H3) | \
    SLOWCOOR_TO_BB(H4) | SLOWCOOR_TO_BB(H5) | SLOWCOOR_TO_BB(H6) | \
    SLOWCOOR_TO_BB(H7) | SLOWCOOR_TO_BB(H8)

#define BBRANK72 \
    BBRANK77 | BBRANK66 | BBRANK55 | BBRANK44 | BBRANK33 | BBRANK22

#define BBRANK62 \
    BBRANK66 | BBRANK55 | BBRANK44 | BBRANK33 | BBRANK22

#define BBRANK52 \
    BBRANK55 | BBRANK44 | BBRANK33 | BBRANK22

#define BBRANK42 \
    BBRANK44 | BBRANK33 | BBRANK22

#define BBRANK32 \
    BBRANK33 | BBRANK22

#define BBRANK27 \
    BBRANK22 | BBRANK33 | BBRANK44 | BBRANK55 | BBRANK66 | BBRANK77

#define BBRANK37 \
    BBRANK33 | BBRANK44 | BBRANK55 | BBRANK66 | BBRANK77

#define BBRANK47 \
    BBRANK44 | BBRANK55 | BBRANK66 | BBRANK77

#define BBRANK57 \
    BBRANK55 | BBRANK66 | BBRANK77

#define BBRANK67 \
    BBRANK66 | BBRANK77

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//
// util.c
//
COMMAND(LearnPsqtFromPgn);

COMMAND(GeneratePositionAndBestMoveSuite);

CHAR *
WalkPV(SEARCHER_THREAD_CONTEXT *ctx);

CHAR *
ReadNextGameFromPgnFile(FILE *pf);

COOR
DistanceBetweenSquares(COOR a, COOR b);

void CDECL
Trace(CHAR *szMessage, ...);

void CDECL
Log(CHAR *szMessage, ...);

void CDECL
Bug(CHAR *szMessage, ...);

char *
FindChunk(char *sz, ULONG uTargetChunk);

FLAG
BufferIsZeroed(BYTE *p, ULONG u);

char *
ColorToString(ULONG u);

char *
CoorToString(COOR c);

char *
ScoreToString(SCORE iScore);

char *
TimeToString(double d);

ULONG
AcquireSpinLock(volatile ULONG *pSpinlock);

FLAG
TryAcquireSpinLock(volatile ULONG *pSpinlock);

void
ReleaseSpinLock(volatile ULONG *pSpinLock);

BYTE
Checksum(BYTE *p, ULONG uSize);

FLAG
BackupFile(CHAR *szFile);

void
UtilPrintPV(SEARCHER_THREAD_CONTEXT *ctx,
            SCORE iAlpha,
            SCORE iBeta,
            SCORE iScore,
            MOVE mv);

#define CANNOT_INITIALIZE_SPLIT           (1)
#define INCONSISTENT_POSITION             (2)
#define UNEXPECTED_SYSTEM_CALL_FAILURE    (3)
#define SHOULD_NOT_GET_HERE               (4)
#define GOT_ILLEGAL_MOVE_WHILE_PONDERING  (5)
#define CANNOT_OFFICIALLY_MAKE_MOVE       (6)
#define DETECTED_INCORRECT_INITIALIZATION (7)
#define INCONSISTENT_STATE                (8)
#define FATAL_ACCESS_DENIED               (9)
#define TESTCASE_FAILURE                  (10)
#define INITIALIZATION_FAILURE            (11)

void
UtilPanic(ULONG uPanicCode,
          POSITION *pos,
          void *a1,
          void *a2,
          void *a3,
          char *file, ULONG line);


//
// main.c
//
#define LOGFILE_NAME                "typhoon.log"
extern FILE *g_pfLogfile;

void
Banner(void);

FLAG
PreGameReset(FLAG fResetBoard);

//
// system dependent exports (see win32.c or fbsd.c)
//
typedef ULONG (THREAD_ENTRYPOINT)(ULONG);

#ifdef DEBUG
ULONG
GetHeapMemoryUsage(void);
#endif

void
SystemDebugBreakpoint(void);

CHAR *
SystemStrDup(CHAR *p);

double
SystemTimeStamp(void);

FLAG
SystemDoesFileExist(CHAR *szFilename);

void
SystemDeferExecution(ULONG uMs);

void
SystemFreeMemory(void *pMem);

void *
SystemAllocateMemory(ULONG dwSizeBytes);

FLAG
SystemMakeMemoryReadOnly(void *pMemory, ULONG dwSizeBytes);

FLAG
SystemMakeMemoryNoAccess(void *pMemory, ULONG dwSizeBytes);

FLAG
SystemMakeMemoryReadWrite(void *pMemory, ULONG dwSizeBytes);

FLAG
SystemDependentInitialization(void);

UINT64 FASTCALL
SystemReadTimeStampCounter(void);

//
// This routine _must_ implement a full memory fence -- it is used in
// util.c to implement spinlocks.
//
FLAG
SystemCreateThread(THREAD_ENTRYPOINT *pEntry, ULONG uParam, ULONG *puHandle);

FLAG
SystemWaitForThreadToExit(ULONG uThreadHandle);

FLAG
SystemGetThreadExitCode(ULONG uThreadHandle, ULONG *puCode);

FLAG
SystemDeleteThread(ULONG uThreadHandle);

CHAR *
SystemGetDateString(void);

CHAR *
SystemGetTimeString(void);

FLAG
SystemCopyFile(CHAR *szSource, CHAR *szDest);

FLAG
SystemDeleteFile(CHAR *szFile);

ULONG
SystemCreateLock(void);

FLAG
SystemDeleteLock(ULONG u);

FLAG
SystemBlockingWaitForLock(ULONG u);

FLAG
SystemReleaseLock(ULONG u);

ULONG
SystemCreateSemaphore(ULONG u);

FLAG
SystemDeleteSemaphore(ULONG u);

void
SystemReleaseSemaphoreResource(ULONG u);

void
SystemObtainSemaphoreResource(ULONG u);


//
// fen.c
//
#define STARTING_POSITION_IN_FEN \
    "rnbqkbnr/pppppppp/--------/8/8/--------/PPPPPPPP/RNBQKBNR w KQkq - 0 1"

FLAG
LooksLikeFen(char *szFen);

char *
PositionToFen(POSITION *p);

FLAG
FenToPosition(POSITION *p, char *szFen);

//
// testfen.c
//
#ifdef TEST
void
TestFenCode(void);
#endif

//
// piece.c
//
// INVERTED VALUE == (VALUE_QUEEN / VALUE_PIECE) * VALUE_PAWN;
#define VALUE_PAWN            100
#define INVERT_PAWN           900
#define VALUE_KNIGHT          300
#define INVERT_KNIGHT         300
#define VALUE_BISHOP          300
#define INVERT_BISHOP         300
#define VALUE_ROOK            500
#define INVERT_ROOK           180
#define VALUE_QUEEN           975
#define INVERT_QUEEN          100
#define VALUE_KING            (INFINITY)
#define INVERT_KING           1

#define VALUE_FULL_ARMY       (8 * VALUE_PAWN) + (2 * VALUE_KNIGHT) + \
                              (2 * VALUE_BISHOP) + (2 * VALUE_ROOK) + \
                              VALUE_QUEEN + VALUE_KING
#define VALUE_MAX_ARMY        (9 * VALUE_QUEEN) + (2 * VALUE_KNIGHT) + \
                              (2 * VALUE_BISHOP) + (2 * VALUE_ROOK) + \
                              VALUE_KING

typedef struct _PIECE_DATA
{
    ULONG uValue;
    ULONG uValueOver100;
    ULONG uInvertedValue;
    CHAR *szName;
} PIECE_DATA;

extern PIECE_DATA g_PieceData[8];

#define PIECE_VALUE_OVER_100(p) (g_PieceData[PIECE_TYPE(p)].uValueOver100)
extern ULONG
PieceValueOver100(PIECE p);

#define PIECE_VALUE(p)          (g_PieceData[PIECE_TYPE(p)].uValue)
extern ULONG
PieceValue(PIECE p);

#define INVERTED_PIECE_VALUE(p) (g_PieceData[PIECE_TYPE(p)].uInvertedValue)
extern ULONG
PieceInvertedValue(PIECE p);

CHAR *
PieceAbbrev(PIECE p);

//
// board.c
//
FLAG
VerifyPositionConsistency(POSITION *pos, FLAG fContinueOnError);

FLAG
PositionsAreEquivalent(POSITION *p1, POSITION *p2);

CHAR *
DrawTextBoardFromPosition(POSITION *pos);

void
DumpPosition(POSITION *pos);

CHAR *
CastleInfoString(BITV bv);

void
SetRootToInitialPosition(void);

//
// move.c
//
void
SlidePiece(POSITION *pos, COOR cFrom, COOR cTo);

PIECE
LiftPiece(POSITION *pos, COOR cSquare);

void
PlacePiece(POSITION *pos, COOR cSquare, PIECE pPiece);

FLAG
MakeMove(SEARCHER_THREAD_CONTEXT *ctx,
         MOVE mv);

void
UnmakeMove(SEARCHER_THREAD_CONTEXT *ctx,
           MOVE mv);

FLAG
MakeUserMove(SEARCHER_THREAD_CONTEXT *ctx, MOVE mvUser);

void
DumpMove(ULONG u);

//
// movesup.c
//
#define MOVE_TO_INDEX(mv)  (((mv).uMove & 0xFFFF) + \
                            (0x10000 * GET_COLOR(mv.pMoved)))

COOR
FasterExposesCheck(POSITION *pos,
                   COOR cRemove,
                   COOR cLocation);

COOR
ExposesCheck(POSITION *pos,
             COOR cRemove,
             COOR cLocation);

COOR
ExposesCheckEp(POSITION *pos,
               COOR cTest,
               COOR cIgnore,
               COOR cBlock,
               COOR cKing);

FLAG
IsAttacked(COOR cTest, POSITION *pos, ULONG uSide);

FLAG
InCheck(POSITION *pos, ULONG uSide);

FLAG
SanityCheckMove(POSITION *pos, MOVE mv);

FLAG
LooksLikeFile(CHAR c);

FLAG
LooksLikeRank(CHAR c);

FLAG
LooksLikeCoor(CHAR *szData);

CHAR *
StripMove(CHAR *szMove);

ULONG
LooksLikeMove(CHAR *szData);

void FASTCALL
SelectBestWithHistory(SEARCHER_THREAD_CONTEXT *ctx, ULONG u);

void FASTCALL
SelectBestNoHistory(SEARCHER_THREAD_CONTEXT *ctx, ULONG u);

void FASTCALL
SelectMoveAtRoot(SEARCHER_THREAD_CONTEXT *ctx, ULONG u);

#define NOT_MOVE 0
#define MOVE_ICS 1
#define MOVE_SAN 2

COMMAND(PerftCommand);


//
// testmove.c
//
#ifdef TEST
void
TestLiftPlaceSlidePiece(void);

void
TestExposesCheck(void);

void
TestIsAttacked(void);

void
TestMakeUnmakeMove(void);
#endif

//
// generate.c
//
#define SORT_THESE_FIRST (0x40000000)
#define FIRST_KILLER     (0x20000000)
#define SECOND_KILLER    (0x10000000)
#define THIRD_KILLER     (0x08000000)
#define FOURTH_KILLER    (0x04000000)
#define GOOD_MOVE        (0x02000000)
#define STRIP_OFF_FLAGS  (0x00FFFFFF)

extern const int g_iQKDeltas[9];
extern const int g_iNDeltas[9];
extern const int g_iBDeltas[5];
extern const int g_iRDeltas[5];

void
GenerateMoves(SEARCHER_THREAD_CONTEXT *ctx,
              MOVE mvOrderFirst,
              ULONG uType);

FLAG
WouldGiveCheck(IN SEARCHER_THREAD_CONTEXT *ctx,
               IN MOVE mv);

//
// testgenerate.c
//
#ifdef TEST

void
PlyTest(SEARCHER_THREAD_CONTEXT *ctx,
        ULONG uDepth,
        FLAG fRootPositionInCheck);

void
TestMoveGenerator(void);

void
TestLegalMoveGenerator(void);

#endif

//
// sig.c
//
extern UINT64 g_u64SigSeeds[128][7][2];
extern UINT64 g_u64PawnSigSeeds[128][2];
extern UINT64 g_u64CastleSigSeeds[16];
extern UINT64 g_u64EpSigSeeds[9];

void
InitializeSigSystem(void);

UINT64
ComputePawnSig(POSITION *pos);

UINT64
ComputeSig(POSITION *pos);

//
// mersenne.c
//
void
seedMT(unsigned int seed);

unsigned int
reloadMT(void);

unsigned int
randomMT(void);

//
// data.c
//
typedef struct _VECTOR_DELTA
{
    UCHAR iVector[2];
    signed char iDelta;
    signed char iNegDelta;
}
VECTOR_DELTA;

extern ULONG g_uDistance[256];
extern ULONG *g_pDistance;
extern VECTOR_DELTA g_VectorDelta[256];
extern VECTOR_DELTA *g_pVectorDelta;
extern CHAR g_SwapTable[14][32][32];
extern SCORE _PSQT[14][128];
extern ULONG g_uSearchSortLimits[];
extern MOVE NULLMOVE;
extern MOVE HASHMOVE;
extern MOVE RECOGNMOVE;
extern MOVE DRAWMOVE;
extern MOVE MATEMOVE;
extern FLAG g_fIsWhiteSquare[128];
extern BITBOARD BBFILE[8];
extern BITBOARD BBRANK[9];
extern BITBOARD BBWHITESQ;
extern BITBOARD BBBLACKSQ;
extern BITBOARD BBLEFTSIDE;
extern BITBOARD BBRIGHTSIDE;
extern BITBOARD BBSQUARE[64];
extern BITBOARD BBROOK_PAWNS;
extern BITBOARD BBPRECEEDING_RANKS[8][2];
extern BITBOARD BBADJACENT_FILES[8];
extern BITBOARD BBADJACENT_RANKS[9];

void
InitializeWhiteSquaresTable(void);

void
InitializeVectorDeltaTable(void);

void
InitializeSwapTable(void);

void
InitializeDistanceTable(void);

void
InitializeSearchDepthArray(void);

ULONG
GetSearchSortLimit(ULONG);

#ifdef DEBUG
#define SEARCH_SORT_LIMIT(x)    (GetSearchSortLimit((x)))
#else
#define SEARCH_SORT_LIMIT(x)    (g_uSearchSortLimits[(x)])
#endif

#ifdef DEBUG
ULONG CheckVectorWithIndex(int i, ULONG uColor);
#define CHECK_VECTOR_WITH_INDEX(i, color) \
    CheckVectorWithIndex(i, color)

int DirectionBetweenSquaresWithIndex(int i);
#define CHECK_DELTA_WITH_INDEX(i) \
    DirectionBetweenSquaresWithIndex(i)

int DirectionBetweenSquaresFromTo(COOR, COOR);
#define DIRECTION_BETWEEN_SQUARES(from, to) \
    DirectionBetweenSquaresFromTo(from, to)

int NegativeDirectionBetweenSquaresWithIndex(int i);
#define NEG_DELTA_WITH_INDEX(i) \
    NegativeDirectionBetweenSquaresWithIndex(i)

FLAG IsSquareWhite(COOR c);
#define IS_SQUARE_WHITE(c) \
    IsSquareWhite(c)

#else
#define CHECK_VECTOR_WITH_INDEX(i, color) \
    (g_pVectorDelta[(i)].iVector[(color)])

#define CHECK_DELTA_WITH_INDEX(i) \
    (g_pVectorDelta[(i)].iDelta)

#define DIRECTION_BETWEEN_SQUARES(cFrom, cTo) \
    CHECK_DELTA_WITH_INDEX((int)(cFrom) - (int)(cTo))

#define NEG_DELTA_WITH_INDEX(i) \
    (g_pVectorDelta[(i)].iNegDelta)

#define IS_SQUARE_WHITE(c) \
    (g_fIsWhiteSquare[(c)])
#endif

//
// san.c
//
MOVE
ParseMoveSan(CHAR *szInput,
             POSITION *pos);

CHAR *
MoveToSan(MOVE mv, POSITION *pos);

//
// testsan.c
//
void
TestSan(void);

//
// list.c
//
void
InitializeListHead(IN DLIST_ENTRY *pListHead);

FLAG
IsListEmpty(IN DLIST_ENTRY *pListHead);

FLAG
RemoveEntryList(IN DLIST_ENTRY *pEntry);

DLIST_ENTRY *
RemoveHeadList(IN DLIST_ENTRY *pListHead);

DLIST_ENTRY *
RemoveTailList(IN DLIST_ENTRY *pListHead);

void
InsertTailList(IN DLIST_ENTRY *pListHead,
               IN DLIST_ENTRY *pEntry);

void
InsertHeadList(IN DLIST_ENTRY *pListHead,
               IN DLIST_ENTRY *pEntry);

//
// command.c
//
void
ParseUserInput(FLAG fSearching);

FLAG
InitializeCommandSystem(void);

void
CleanupCommandSystem(void);

//
// input.c
//
void
InitInputSystemInBatchMode(void);

ULONG
InitInputSystemWithDedicatedThread(void);

void
PushNewInput(CHAR *buf);

CHAR *
PeekNextInput(void);

CHAR *
ReadNextInput(void);

CHAR *
BlockingReadInput(void);

ULONG
NumberOfPendingInputEvents(void);

volatile extern FLAG g_fExitProgram;

//
// ics.c
//
MOVE
ParseMoveIcs(CHAR *szInput, POSITION *pos);

CHAR *
MoveToIcs(MOVE mv);

//
// testics.c
//
void
TestIcs(void);

//
// gamelist.c
//
typedef enum _ERESULT
{
    RESULT_BLACK_WON = -1,
    RESULT_DRAW = 0,
    RESULT_WHITE_WON = 1,
    RESULT_IN_PROGRESS,
    RESULT_ABANDONED,
    RESULT_UNKNOWN
} ERESULT;

typedef struct _GAME_RESULT
{
    ERESULT eResult;
    CHAR szDescription[256];
} GAME_RESULT;

typedef struct _GAME_PLAYER
{
    CHAR *szName;
    CHAR *szDescription;
    FLAG fIsComputer;
    ULONG uRating;
}
GAME_PLAYER;

typedef struct _GAME_HEADER
{
    CHAR *szGameDescription;
    CHAR *szLocation;
    GAME_PLAYER sPlayer[2];
    FLAG fGameIsRated;
    UINT64 u64OpeningSig;
    ERESULT eResult;
    CHAR *szResultComment;
    CHAR *szInitialFen;
}
GAME_HEADER;

typedef struct _GAME_MOVE
{
    DLIST_ENTRY links;
    ULONG uNumber;
    MOVE mv;
    CHAR *szComment;
    CHAR *szDecoration;
    CHAR *szMoveInSan;
    CHAR *szMoveInIcs;
    CHAR *szUndoPositionFen;
    SCORE iMoveScore;
    UINT64 u64PositionSigAfterMove;
    UINT64 u64PositionSigBeforeMove;
    volatile FLAG fInUse;
}
GAME_MOVE;

typedef struct _GAME_DATA
{
    GAME_HEADER sHeader;
    DLIST_ENTRY sMoveList;
}
GAME_DATA;

extern GAME_DATA g_GameData;

POSITION *
GetRootPosition(void);

FLAG
SetRootPosition(CHAR *szFen);

void
ResetGameList(void);

ULONG
GetMoveNumber(ULONG uColor);

void
SetGameResultAndDescription(ERESULT r, CHAR *sz);

INT
GetGameResult(void);

void
SetMyName(void);

void
SetOpponentsName(CHAR *sz);

void
SetMyRating(ULONG u);

void
SetOpponentsRating(ULONG u);

void
DumpGameList(void);

void
TellGamelistThatIPlayColor(ULONG u);

void
DumpPgn(void);

FLAG
LoadPgn(CHAR *szPgn);

ULONG
CountOccurrancesOfSigInOfficialGameList(UINT64 u64Sig);

FLAG
DoesSigAppearInOfficialGameList(UINT64 u64Sig);

FLAG
OfficiallyTakebackMove(void);

FLAG
OfficiallyMakeMove(MOVE mv, SCORE iMoveScore, FLAG fFast);

GAME_MOVE *
GetNthOfficialMoveRecord(ULONG n);

void
MakeStatusLine(void);

FLAG
IsLegalDrawByRepetition(void);

//
// script.c
//
COMMAND(ScriptCommand);

COMMAND(SolutionCommand);

COMMAND(AvoidCommand);

COMMAND(IdCommand);

void
PostMoveTestSuiteReport(SEARCHER_THREAD_CONTEXT *);

FLAG
CheckTestSuiteMove(MOVE mv, SCORE iScore, ULONG uDepth);

FLAG
WeAreRunningASuite(void);


//
// vars.c
//
COMMAND(SetCommand);

//
// root.c
//
extern ULONG g_uSoftExtendLimit;
extern ULONG g_uHardExtendLimit;
extern volatile MOVE_TIMER g_MoveTimer;
extern ULONG g_uExtensionReduction[MAX_PLY_PER_SEARCH];

#ifdef PERF_COUNTERS
#define KEEP_TRACK_OF_FIRST_MOVE_FHs(x)                \
    ctx->sCounters.tree.u64BetaCutoffs++;              \
    if (x)                                             \
    {                                                  \
       ctx->sCounters.tree.u64BetaCutoffsOnFirstMove++;\
    }
#else
#define KEEP_TRACK_OF_FIRST_MOVE_FHs(x)
#endif

#define GAME_NOT_OVER 0
#define GAME_WHITE_WON 1
#define GAME_BLACK_WON 2
#define GAME_DRAW_STALEMATE 3
#define GAME_DRAW_REPETITION 4
#define GAME_ONE_LEGAL_MOVE 5
#define GAME_DRAW_FIFTY_MOVES_WO_PROGRESS 6

GAME_RESULT
Think(POSITION *pos);

GAME_RESULT
Ponder(POSITION *pos);

GAME_RESULT
Iterate(SEARCHER_THREAD_CONTEXT *ctx);

void
SetMoveTimerForSearch(FLAG fSwitchOver, ULONG uColor);

void
SetMoveTimerToThinkForever(void);

void
ClearRootNodecountHash(void);

//
// draw.c
//
FLAG
IsDraw(SEARCHER_THREAD_CONTEXT *ctx);


//
// search.c
//
#define QPLIES_OF_NON_CAPTURE_CHECKS (1)
#define FUTILITY_BASE_MARGIN         (50) // + ctx->uPositional (min 100)
#define DO_IID
#define IID_R_FACTOR                 (TWO_PLY + HALF_PLY)

#ifndef MP
#define WE_SHOULD_STOP_SEARCHING (g_MoveTimer.bvFlags & TIMER_STOPPING)
#else
#define WE_SHOULD_STOP_SEARCHING ((g_MoveTimer.bvFlags & TIMER_STOPPING) || \
                                  (ThreadUnderTerminatingSplit(ctx)))
#endif

SCORE FASTCALL
QSearch(SEARCHER_THREAD_CONTEXT *ctx,
        SCORE iAlpha,
        SCORE iBeta);

SCORE FASTCALL
Search(SEARCHER_THREAD_CONTEXT *ctx,
       SCORE iAlpha,
       SCORE iBeta,
       ULONG uDepth);


//
// searchsup.c
//
SCORE
ComputeMoveScore(IN SEARCHER_THREAD_CONTEXT *ctx,
                 IN MOVE mv,
                 IN ULONG uMoveNum);

FLAG
ThreadUnderTerminatingSplit(SEARCHER_THREAD_CONTEXT *);

FLAG
WeShouldDoHistoryPruning(IN SCORE iRoughEval,
                         IN SCORE iAlpha,
                         IN SCORE iBeta,
                         IN SEARCHER_THREAD_CONTEXT *ctx,
                         IN ULONG uRemainingDepth,
                         IN ULONG uLegalMoves,
                         IN MOVE mv,
                         IN ULONG uMoveNum,
                         IN INT iExtend);

FLAG
WeShouldTryNullmovePruning(IN SEARCHER_THREAD_CONTEXT *ctx,
                           IN SCORE iAlpha,
                           IN SCORE iBeta,
                           IN SCORE iRoughEval,
                           IN ULONG uNullDepth);

FLAG
TryNullmovePruning(IN OUT SEARCHER_THREAD_CONTEXT *ctx,
                   IN OUT FLAG *pfThreat,
                   IN SCORE iAlpha,
                   IN SCORE iBeta,
                   IN ULONG uNullDepth,
                   IN OUT INT *piOrigExtend,
                   OUT SCORE *piNullScore);

void
UpdatePV(SEARCHER_THREAD_CONTEXT *ctx, MOVE mv);

FLAG
CheckInputAndTimers(IN SEARCHER_THREAD_CONTEXT *ctx);

void
ComputeReactionToCheckExtension(IN OUT SEARCHER_THREAD_CONTEXT *ctx,
                                IN ULONG uGenFlags,
                                IN ULONG uMoveNum,
                                IN SCORE iRoughEval,
                                IN SCORE iAlpha,
                                IN OUT INT *piExtend,
                                IN OUT INT *piOrigExtend);

void
ComputeMoveExtension(IN OUT SEARCHER_THREAD_CONTEXT *ctx,
                     IN SCORE iAlpha,
                     IN SCORE iBeta,
                     IN ULONG uMoveNum,
                     IN SCORE iRoughEval,
                     IN ULONG uDepth,
                     IN OUT INT *piExtend);

SCORE
RescoreMovesViaSearch(IN SEARCHER_THREAD_CONTEXT *ctx,
                      IN ULONG uDepth,
                      IN SCORE iAlpha,
                      IN SCORE iBeta);

FLAG
MateDistancePruningCutoff(IN ULONG uPly,
                          IN FLAG fInCheck,
                          IN OUT SCORE *piBestScore,
                          IN OUT SCORE *piAlpha,
                          IN OUT SCORE *piBeta);

FLAG
CommonSearchInit(IN SEARCHER_THREAD_CONTEXT *ctx,
                 IN OUT SCORE *piAlpha,
                 IN OUT SCORE *piBeta,
                 IN OUT SCORE *piScore);

ULONG
SelectNullmoveRFactor(IN SEARCHER_THREAD_CONTEXT *ctx,
                      IN INT uDepth);

#define VERIFY_BEFORE (1)
#define VERIFY_AFTER  (2)

FLAG
SanityCheckMoves(IN SEARCHER_THREAD_CONTEXT *ctx,
                 IN ULONG uCurrent,
                 IN ULONG uType);


//
// testsearch.c
//
FLAG
TestSearch(void);

//
// see.c
//
#define SEE_HEAPS

SCORE
SEE(POSITION *pos,
    MOVE mv);

typedef struct _SEE_THREESOME
{
    PIECE pPiece;
    COOR cLoc;
    ULONG uVal;
} SEE_THREESOME;

typedef struct _SEE_LIST
{
    ULONG uCount;
    SEE_THREESOME data[16];
}
SEE_LIST;

SCORE
ControlsSquareMinusPiece(ULONG uSide,
                         POSITION *pos,
                         COOR c,
                         COOR cIgnore);

//
// testsee.c
//
SCORE
DebugSEE(POSITION *pos,
         MOVE mv);

void
TestGetAttacks(void);

//
// hash.c
//
#define NUM_HASH_ENTRIES_PER_LINE     4
#define HASH_FLAG_EXACT               0x1
#define HASH_FLAG_LOWER               0x2
#define HASH_FLAG_UPPER               0x4
#define HASH_FLAG_VALID_BOUNDS        0x7
#define HASH_FLAG_THREAT              0x8
#define HASH_FLAG_DIRTY               0xF0

typedef struct _HASH_ENTRY
{
    MOVE mv;                         // 0 1 2 3
    UCHAR uDepth;                    // 4
    UCHAR bvFlags;                   // 5 ==> d  d  d  d | thr up low exact
    signed short iValue;             // 6 7
    UINT64 u64Sig;                   // 8 9 A B C D E F == 16 bytes
} HASH_ENTRY;

FLAG
InitializeHashSystem(void);

void
CleanupHashSystem(void);

void
ClearHashTable(void);

void
DirtyHashTable(void);

void
StoreLowerBound(MOVE mvBestMove,
           POSITION *pos,
           SCORE iValue,
           ULONG uDepth,
           FLAG fThreat);
void
StoreExactScore(MOVE mvBestMove,
            POSITION *pos,
          SCORE iValue,
          ULONG uDepth,
          FLAG fThreat,
          ULONG uPly);

void
StoreUpperBound(//MOVE mvBestMove,
           POSITION *pos,
           SCORE iValue,
           ULONG uDepth,
           FLAG fThreat);

HASH_ENTRY *
HashLookup(SEARCHER_THREAD_CONTEXT *ctx,
           ULONG uDepth,
           ULONG uNextDepth,
           SCORE iAlpha,
           SCORE iBeta,
           FLAG *pfThreat,
           FLAG *pfAvoidNull,
           MOVE *pHashMove,
           SCORE *piScore);

COOR
CheckHashForDangerSquare(POSITION *pos);

MOVE
GetPonderMove(POSITION *pos);

extern ULONG g_uHashTableSizeEntries;
extern ULONG g_uHashTableSizeBytes;
extern HASH_ENTRY *g_pHashTable;

//
// testhash.c
//
void
AnalyzeFullHashTable(void);

//
// positionhash.c
//
// IDEA: store "mate threat" flag in here?
// IDEA: store "king safety" numbers in here?
//
typedef struct _POSITION_HASH_ENTRY {
    UINT64 u64Sig;
    UCHAR cEnprise[2];
    UCHAR uEnpriseCount[2];
    UCHAR cTrapped[2];
} POSITION_HASH_ENTRY;

void
InitializePositionHashSystem(void);

void
CleanupPositionHashSystem(void);

void
StoreEnprisePiece(POSITION *pos, COOR cSquare);

void
StoreTrappedPiece(POSITION *pos, COOR cSquare);

COOR
GetEnprisePiece(POSITION *pos, ULONG uSide);

ULONG
GetEnpriseCount(POSITION *pos, ULONG uSide);

COOR
GetTrappedPiece(POSITION *pos, ULONG uSide);

FLAG
SideCanStandPat(POSITION *pos, ULONG uSide);

ULONG
ValueOfMaterialInTroubleDespiteMove(POSITION *pos, ULONG uSide);

ULONG
ValueOfMaterialInTroubleAfterNull(POSITION *pos, ULONG uSide);

//
// pawnhash.c
//
#define COOR_TO_BIT(x)       ((x) & 0x7) + ((0x7 - ((x) >> 4)) << 3)

void
ClearPawnHashStats(void);

void
ReportPawnHashStats(void);

PAWN_HASH_ENTRY *
PawnHashLookup(SEARCHER_THREAD_CONTEXT *ctx);

//
// eval.c
//
#define LAZY_EVAL
#define LAZE_EVAL_BASE_SCORE 10
extern const int g_iAhead[2];
extern const int g_iBehind[2];

ULONG 
DNABufferSizeBytes();

char *
ExportEvalDNA();

FLAG
WriteEvalDNA(char *szFilename);

FLAG
ImportEvalDNA(char *p);

FLAG
ReadEvalDNA(char *szFilename);



SCORE
Eval(SEARCHER_THREAD_CONTEXT *, SCORE, SCORE);

FLAG
EvalPasserRaces(POSITION *,
                PAWN_HASH_ENTRY *);

ULONG
CountKingSafetyDefects(POSITION *pos,
                       ULONG uSide);

//
// testeval.c
//
#ifdef EVAL_DUMP
void
TestEval(void);

void
EvalTraceReport(void);

void
EvalTrace(ULONG uColor, PIECE p, COOR c, SCORE iVal, CHAR *szMessage);

SCORE
EvalSigmaForPiece(POSITION *pos, COOR c);

void
EvalTraceClear(void);

void
TestEvalWithSymmetry(void);

#define EVAL_TERM(COL, PIE, COO, VAL, ADJ, MESS) \
    (VAL) += (ADJ); \
    EvalTrace((COL), (PIE), (COO), (ADJ), (MESS));
#else
#define EVAL_TERM(COL, PIE, COO, VAL, ADJ, MESS) \
    (VAL) += (ADJ);
#endif

//
// bitboard.c
//
void
InitializeBitboards(void);

ULONG CDECL
SlowCountBits(BITBOARD bb);

ULONG CDECL
DeBruijnFirstBit(BITBOARD bb);

ULONG CDECL
SlowFirstBit(BITBOARD bb);

ULONG CDECL
SlowLastBit(BITBOARD bb);

#ifdef CROUTINES
#define CountBits SlowCountBits
#define FirstBit SlowFirstBit
#define LastBit SlowLastBit
#endif

COOR
CoorFromBitBoardRank8ToRank1(BITBOARD *pbb);

COOR
CoorFromBitBoardRank1ToRank8(BITBOARD *pbb);

//
// x86.asm
//
ULONG CDECL
CountBits(BITBOARD bb);

ULONG CDECL
FirstBit(BITBOARD bb);

ULONG CDECL
LastBit(BITBOARD bb);

ULONG CDECL
LockCompareExchange(volatile void *pDest,
                    ULONG uExch,
                    ULONG uComp);

ULONG CDECL
LockIncrement(volatile void *pDest);

ULONG CDECL
LockDecrement(volatile void *pDest);

FLAG CDECL
CanUseParallelOpcodes();

ULONG CDECL
ParallelCompareUlong(ULONG uComparand, void *pComparators);

ULONG CDECL
ParallelCompareVector(void *pComparand, void *pComparators);

void CDECL
GetAttacks(SEE_LIST *pList,
           POSITION *pos,
           COOR cSquare,
           ULONG uSide);

void CDECL
SlowGetAttacks(SEE_LIST *pList,
               POSITION *pos,
               COOR cSquare,
               ULONG uSide);
#ifdef CROUTINES
#define GetAttacks SlowGetAttacks
#endif

#ifdef _X86_
//
// Note: this is most of the stuff that x86.asm assumes about the
// internal data structures.  If any of this fails then either the
// assembly language code needs to be updated or you need to use the C
// version of the routine in see.c instead.
//
#define ASSERT_ASM_ASSUMPTIONS \
    ASSERT(VALUE_PAWN == 100); \
    ASSERT(OFFSET_OF(uCount, SEE_LIST) == 0); \
    ASSERT(OFFSET_OF(data, SEE_LIST) == 4); \
    ASSERT(sizeof(SEE_THREESOME) == 12); \
    ASSERT(OFFSET_OF(pPiece, SEE_THREESOME) == 0); \
    ASSERT(OFFSET_OF(cLoc, SEE_THREESOME) == 4); \
    ASSERT(OFFSET_OF(uVal, SEE_THREESOME) == 8); \
    ASSERT(OFFSET_OF(cNonPawns, POSITION) == 0x478); \
    ASSERT(OFFSET_OF(uNonPawnCount, POSITION) == 0x500); \
    ASSERT(OFFSET_OF(rgSquare, POSITION) == 0); \
    ASSERT(sizeof(SQUARE) == 8); \
    ASSERT(sizeof(VECTOR_DELTA) == 4); \
    ASSERT(sizeof(g_VectorDelta) == 256 * 4); \
    ASSERT(OFFSET_OF(iVector, VECTOR_DELTA) == 0); \
    ASSERT(OFFSET_OF(iDelta, VECTOR_DELTA) == 2); \
    ASSERT(OFFSET_OF(iNegDelta, VECTOR_DELTA) == 3); \
    ASSERT(sizeof(g_PieceData) == 8 * 4 * 4); \
    ASSERT(OFFSET_OF(uValue, PIECE_DATA) == 0);
#else
#define ASSERT_ASM_ASSUMPTIONS
#endif

//
// testbitboard.c
//
void
TestBitboards(void);

//
// dynamic.c
//
extern ULONG g_HistoryCounters[14][128];

ULONG
GetMoveFailHighPercentage(MOVE mv);

void
UpdateDynamicMoveOrdering(SEARCHER_THREAD_CONTEXT *ctx,
                          ULONG uRemainingDepth,
                          MOVE mvBest,
                          SCORE iScore,
                          ULONG uCurrent);

void
NewKillerMove(SEARCHER_THREAD_CONTEXT *ctx, MOVE mv, SCORE iScore);

FLAG
InitializeDynamicMoveOrdering(void);

void
CleanupDynamicMoveOrdering(void);

void
ClearDynamicMoveOrdering(void);

void
MaintainDynamicMoveOrdering(void);

void
IncrementMoveHistoryCounter(MOVE mv, ULONG u);

void
DecrementMoveHistoryCounter(MOVE mv, ULONG u);

//
// split.c
//
extern volatile ULONG g_uNumHelpersAvailable;
extern ULONG g_uNumHelperThreads;

FLAG
InitializeParallelSearch(void);

FLAG
CleanupParallelSearch(void);

void
ClearHelperThreadIdleness(void);

void
DumpHelperIdlenessReport(void);

SCORE
StartParallelSearch(IN SEARCHER_THREAD_CONTEXT *ctx,
                    IN OUT SCORE *piAlpha,
                    IN SCORE iBeta,
                    IN OUT SCORE *piBestScore,
                    IN OUT MOVE *pmvBest,
                    IN ULONG uMoveNum,
                    IN INT iPositionExtend,
                    IN ULONG uDepth);

void
InitializeSearcherContext(POSITION *pos, SEARCHER_THREAD_CONTEXT *ctx);

void
ReInitializeSearcherContext(POSITION *pos, SEARCHER_THREAD_CONTEXT *ctx);

void
InitializeLightweightSearcherContext(POSITION *pos,
                                     LIGHTWEIGHT_SEARCHER_CONTEXT *ctx);

//
// book.c
//

#define BOOK_PROBE_MISS_LIMIT  (7)
#define FLAG_DISABLED          (1)
#define FLAG_ALWAYSPLAY        (2)
#define FLAG_DELETED           (4)

#define BOOKMOVE_SELECT_MOVE   (1)
#define BOOKMOVE_DUMP          (2)

#pragma pack(4)
typedef struct _BOOK_ENTRY
{
    UINT64 u64Sig;                            // 8 bytes
    UINT64 u64NextSig;                        // 8 bytes
    MOVE mvNext;                              // 4 bytes
    ULONG uWins;                              // 4 bytes
    ULONG uDraws;                             // 4 bytes
    ULONG uLosses;                            // 4 bytes
    BITV bvFlags;                             // 4 bytes
}
BOOK_ENTRY;
#pragma pack()

typedef struct _OPENING_NAME_MAPPING
{
    UINT64 u64Sig;
    CHAR *szString;
}
OPENING_NAME_MAPPING;

#define BOOK_EDITING_RECORD       "bkedit.edt"
#define OPENING_LEARNING_FILENAME "bklearn.bin"

typedef struct _OPENING_LEARNING_ENTRY
{
    UINT64 u64Sig;
    ULONG uWhiteWins;
    ULONG uDraws;
    ULONG uBlackWins;
}
OPENING_LEARNING_ENTRY;

FLAG
InitializeOpeningBook(void);

void
ResetOpeningBook(void);

void
CleanupOpeningBook(void);

MOVE
BookMove(POSITION *pos,
         BITV bvFlags);

COMMAND(BookCommand);

extern ULONG g_uBookProbeFailures;
extern FLAG g_fTournamentMode;
extern CHAR *g_szBookName;

//
// bench.c
//
COMMAND(BenchCommand);

//
// testdraw.c
//
void
TestDraw(void);

//
// probe.c
//
FLAG
ProbeEGTB(SEARCHER_THREAD_CONTEXT *ctx, SCORE *score);

void
InitializeEGTB(void);

void
CleanupEGTB(void);

//
// dumptree.c
//
#ifdef DUMP_TREE

void
InitializeTreeDump(void);

void
CleanupTreeDump(void);

void
DTEnterNode(SEARCHER_THREAD_CONTEXT *ctx,
            ULONG uDepth,
            FLAG fIsQNode,
            SCORE iAlpha,
            SCORE iBeta);

void
DTLeaveNode(SEARCHER_THREAD_CONTEXT *ctx,
            FLAG fQNode,
            SCORE iBestScore,
            MOVE mvBestMove);

void CDECL
DTTrace(ULONG uPly, CHAR *szMessage, ...);

#define DTTRACE(...) DTTrace(ctx->uPly, __VA_ARGS__)

#else

#define DTTRACE(...)

#define DTEnterNode(...)

#define DTLeaveNode(...)

#define InitializeTreeDump(...)

#define CleanupTreeDump(...)

#endif

//
// testsup.c
//
FLAG
IsBoardLegal(POSITION *pos);

void
GenerateRandomLegalPosition(POSITION *pos);

void
GenerateRandomLegalSymetricPosition(POSITION *pos);

//
// recogn.c
//
#define UNRECOGNIZED (0)
#define RECOGN_EXACT (1)
#define RECOGN_UPPER (2)
#define RECOGN_LOWER (3)
#define RECOGN_EGTB  (4)

void
InitializeInteriorNodeRecognizers(void);

ULONG
RecognLookup(SEARCHER_THREAD_CONTEXT *ctx,
             SCORE *piScore,
             FLAG fProbeEGTB);

#ifdef EVAL_HASH
void
ClearEvalHashStats(void);

void
ReportEvalHashStats(void);

SCORE
ProbeEvalHash(SEARCHER_THREAD_CONTEXT *ctx);

SCORE
GetRoughEvalScore(IN SEARCHER_THREAD_CONTEXT *ctx,
                  IN SCORE iAlpha,
                  IN SCORE iBeta,
                  IN FLAG fUseHash);

void
StoreEvalHash(SEARCHER_THREAD_CONTEXT *ctx, SCORE iScore);
#endif // EVAL_HASH

#endif // CHESS