summaryrefslogtreecommitdiff
path: root/src/eval.c
blob: 76b332cb80076633351846970be556b51176aae2 (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
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
/**
Copyright (c) Scott Gasch

Module Name:

    eval.c

Abstract:

    Position evaluation routines.

Author:

    Scott Gasch ([email protected]) 14 Jun 2004

Revision History:

    $Id: eval.c 357 2008-07-03 16:18:11Z scott $

**/

#include "chess.h"

//
// CountBits and the CoorFromBitBoard{Rank8ToRank1,Rank1ToRank8}
// wrappers (bitboard.c) are real out-of-line asm calls on every one of
// eval.c's ~20 production call sites (passed-pawn detection, bishop-
// pair logic, etc.), hit on every real Eval() call. CountBits' asm
// body (x64.asm) isn't even O(1) popcnt, it's a Kernighan bit-clearing
// loop -- O(popcount) iterations plus call overhead. Redirected via
// #define, the same mechanism chess.h already uses for the OTHER
// direction (#ifdef CROUTINES routes CountBits/FirstBit/LastBit to the
// slow C fallbacks) -- this routes them to the fast inline
// FastCountBits/FastCoorFromBitBoardRank8ToRank1/
// FastCoorFromBitBoardRank1ToRank8 wrappers (chess.h) instead, for
// every existing call site below with no further edits. Those used to
// be duplicated here as file-local statics; promoted to chess.h so
// every other translation unit's bitboard-scan loops (recogn.c,
// board.c, generate.c, movesup.c, probe.c, testmove.c -- added during
// the cNonPawns/cPawns/uPawnCount/uNonPawnCount retirement work) get
// the fast path too, not just eval.c -- confirmed by disassembly that
// those files were still emitting real callq+PLT relocations to the
// slow extern versions before this. Gated on !CROUTINES so the
// CROUTINES debug/comparison build still gets the real (slow,
// cross-checked) implementations.
//
#ifndef CROUTINES
#define CountBits FastCountBits
#define CoorFromBitBoardRank8ToRank1 FastCoorFromBitBoardRank8ToRank1
#define CoorFromBitBoardRank1ToRank8 FastCoorFromBitBoardRank1ToRank8
#endif // !CROUTINES

// Bishop/knight/rook mobility computed during their own eval pass only
// knows about enemy PAWN attacks (bishop/knight) or enemy PAWN+MINOR
// attacks (rook) -- the only attack tables fully populated that early
// -- so a square right next to the enemy king, or (for bishop/knight)
// covered by an enemy piece not yet evaluated, looks "safe" and counts
// toward mobility even though it plainly isn't. Below this many
// candidate squares, don't trust that partial-information count: defer
// to _EvalTrappedPieces, which re-derives a final safe-escape count
// once the full attack picture (both colors, both kings) is in.
// Genuinely 0-mobility pieces are the one exception -- see
// _EvalBishop's comment on why those are scored immediately instead.
#define EVAL_MOBILITY_CAREFULLY_BELOW (3)

//
// To simplify code / maintenance I use the same loop for both colors
// in some places.  These globals coorespond to "ahead of the piece"
// or "behind the piece" for each color.
//
const int g_iAhead[2] = { +1, -1 };
const int g_iBehind[2] = { -1, +1 };

//
// General eval terms
// ---------------------------------------------------------------------------
//
//static SCORE TRADE_PIECES[3][17] =
//{//     0    1    2    3    4    5    6    7    8 | 9..15 -- down piece count
//    {  -1,  90,  81,  73,  67,  62,  57,  52,  50, 50,50,50,50,50,50,50,-1},
//    {  -1, 125, 117, 109, 100,  91,  84,  78,  71, 66,66,66,66,66,66,66,-1},
//    {  -1, 150, 132, 124, 116, 109, 102,  94,  87, 77,77,77,77,77,77,77,-1},
//};

//static SCORE DONT_TRADE_PAWNS[3][9] =
//{//     0    1    2    3    4    5    6    7    8 -- up pawn count
//    { -43, -15,   0,  +3,  +6, +10, +15, +21, +28 },       //           // 0
//    { -63, -25,   0,  +4,  +9, +14, +19, +25, +32 },       //           // 1
//    { -10,   0,   0,  +7, +15, +20, +24, +29, +36 },       //           // 2
//};

static ULONG REDUCED_MATERIAL_DOWN_SCALER[32] =
{
//  none    na      na      m       na      R       2m      na
    0,      0,      0,      0,      0,      0,      0,      0,

//  Rm      3m/Q    2R      R2m     4m/Qm   2Rm     R3m/QR  Q2m
    0,      1,      1,      1,      2,      2,      2,      3,

//  2R2m    R4m/QRm Q3m     2R3m/   QR2m    Q4m     2R4m/   QR3m
//                          Q2R                     Q2Rm
    4,      5,      6,      6,      7,      7,      7,      7,

//  na      Q2R2m   QR4m    na      Q2R3m   na      na      full
    8,      8,      8,      8,      8,      8,      8,      8,
};

//
// Same shape as REDUCED_MATERIAL_DOWN_SCALER (0 with little material left,
// ramping to 8 with a full army) but decays to 0 much sooner -- "haven't
// castled yet" / "minors still at home" are opening-specific concerns that
// stop mattering well before the point where real king danger fades, so
// this table's zero region extends much further up the index range than
// REDUCED_MATERIAL_DOWN_SCALER's does.
//
static ULONG CASTLE_AND_DEVELOPMENT_SCALER[32] =
{
//  none    na      na      m       na      R       2m      na
    0,      0,      0,      0,      0,      0,      0,      0,

//  Rm      3m/Q    2R      R2m     4m/Qm   2Rm     R3m/QR  Q2m
    0,      0,      0,      0,      0,      0,      0,      0,

//  2R2m    R4m/QRm Q3m     2R3m/   QR2m    Q4m     2R4m/   QR3m
//                          Q2R                     Q2Rm
    0,      1,      2,      3,      4,      5,      6,      7,

//  na      Q2R2m   QR4m    na      Q2R3m   na      na      full
    7,      8,      8,      8,      8,      8,      8,      8,
};

static ULONG REDUCED_MATERIAL_UP_SCALER[32] =
{
//  none    na      na      m       na      R       2m      na
    8,      8,      8,      8,      8,      8,      8,      8,

//  Rm      3m/Q    2R      R2m     4m/Qm   2Rm     R3m/QR  Q2m
    8,      7,      7,      7,      7,      6,      6,      5,

//  2R2m    R4m/QRm Q3m     2R3m/   QR2m    Q4m     2R4m/   QR3m
//                          Q2R                     Q2Rm
    4,      3,      3,      3,      2,      2,      2,      1,

//  na      Q2R2m   QR4m    na      Q2R3m   na      na      full
    1,      1,      0,      0,      0,      0,      0,      0,
};

static ULONG PASSER_MATERIAL_UP_SCALER[32] =
{
//  none    na      na      m       na      R       2m      na
    8,      8,      8,      8,      8,      8,      7,      7,

//  Rm      3m/Q    2R      R2m     4m/Qm   2Rm     R3m/QR  Q2m
    7,      6,      7,      5,      4,      5,      4,      3,

//  2R2m    R4m/QRm Q3m     2R3m/   QR2m    Q4m     2R4m/   QR3m
//                          Q2R                     Q2Rm
    2,      2,      1,      1,      0,      0,      0,      0,

//  na      Q2R2m   QR4m    na      Q2R3m   na      na      full
    0,      0,      0,      0,      0,      0,      0,      0,
};

static ULONG MULTIPLE_PASSER_SCALER[9] =
{
//  0     1     2     3     4     5     6     7     8
    0,   32,   27,   22,   18,   11,    8,    4,    2
};

COOR QUEENING_RANK[2] = { 1, 8 };
COOR JUMPING_RANK[2] = { 7, 2 };

//
// Pawn eval terms
// ---------------------------------------------------------------------------
//

// "There is one case which can be treated as positional or material,
// namely the rook's pawn, which differs from other pawns in that it
// can only capture one way instead of two. Since this handicap cannot
// be corrected without the opponent's help, I teach my students to
// regard the rook's pawn as a different piece type, a crippled
// pawn. Database statistics indicate that it is on average worth
// about 15% less than a normal pawn. The difference is enough so that
// it is usually advantageous to make a capture with a rook's pawn,
// promoting it to a knights pawn, even if that produces doubled pawns
// and even if there is no longer a rook on the newly opened rook's
// file."
//                                                --Larry Kaufman, IM
//                                  "Evaluation of Material Imbalance"
//
static SCORE PAWN_CENTRALITY_BONUS[128] =
{
       0,    0,    0,    0,    0,    0,    0,    0,    0,0,0,0,0,0,0,0,
      -5,    0,    0,    0,    0,    0,    0,   -5,    0,0,0,0,0,0,0,0,
      -5,    0,    5,    5,    5,    5,    0,   -5,    0,0,0,0,0,0,0,0,
      -5,    0,    5,    8,    8,    5,    0,   -5,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -5,    0,    5,    8,    8,    5,    0,   -5,    0,0,0,0,0,0,0,0,
      -5,    0,    5,    5,    5,    5,    0,   -5,    0,0,0,0,0,0,0,0,
      -5,    0,    0,    0,    0,    0,    0,   -5,    0,0,0,0,0,0,0,0,
       0,    0,    0,    0,    0,    0,    0,    0,    0,0,0,0,0,0,0,0
};

// Hand-restored 2026-08-30: the DNA-tuned values here had drifted to
// mostly-positive across the board (a shielded backward pawn was scoring
// as a +12..+17 bonus on most files, and several EXPOSED entries were
// less negative than the corresponding SHIELDED ones on the same file --
// i.e. "more exposed" scored better than "less exposed"). Both the
// ASSERT(BACKWARD_SHIELDED_BY_LOCATION[c] < 0) and the analogous EXPOSED
// assert below had been silently commented out rather than investigated.
// Replaced with a monotonic, strictly-negative, rank-mirrored shape:
// backward pawns are always a defect, exposed is always worse than
// shielded at the same rank, and the penalty grows as the pawn advances
// toward the more contested center ranks (4/5) where a backward pawn is
// most exploitable. Table is indexed by absolute square (not
// color-relative), hence the rank2/rank7, rank3/rank6, rank4/rank5
// mirroring -- same as the original layout.
static SCORE BACKWARD_SHIELDED_BY_LOCATION[128] =
{
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0,
      -7,   -5,   -5,   -7,   -7,   -5,   -5,   -7,    0,0,0,0,0,0,0,0,
      -5,   -4,   -4,   -5,   -5,   -4,   -4,   -5,    0,0,0,0,0,0,0,0,
      -4,   -3,   -3,   -4,   -4,   -3,   -3,   -4,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -4,   -3,   -3,   -4,   -4,   -3,   -3,   -4,    0,0,0,0,0,0,0,0,
      -5,   -4,   -4,   -5,   -5,   -4,   -4,   -5,    0,0,0,0,0,0,0,0,
      -7,   -5,   -5,   -7,   -7,   -5,   -5,   -7,    0,0,0,0,0,0,0,0,
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0
};

static SCORE BACKWARD_EXPOSED_BY_LOCATION[128] =
{
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0,
     -12,   -9,   -9,  -11,  -11,   -9,   -9,  -12,    0,0,0,0,0,0,0,0,
      -9,   -7,   -7,   -9,   -9,   -7,   -7,   -9,    0,0,0,0,0,0,0,0,
      -7,   -6,   -6,   -7,   -7,   -6,   -6,   -7,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -7,   -6,   -6,   -7,   -7,   -6,   -6,   -7,    0,0,0,0,0,0,0,0,
      -9,   -7,   -7,   -9,   -9,   -7,   -7,   -9,    0,0,0,0,0,0,0,0,
     -12,   -9,   -9,  -11,  -11,   -9,   -9,  -12,    0,0,0,0,0,0,0,0,
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0
};

//
// "The first statement I can confirm is that doubled pawns are indeed
// on average undesirable.  However this statistic needs to be broken
// down to be useful.  Doubled pawns themselves are really more
// serious than this generally, but when your pawns are doubled you
// automatically get an extra half-open file for your rooks (or queen,
// but the queen can also use diagonals).  So it follows logically
// that the net cost of doubled pawns is much greater in the absence
// of major pieces.  The database shows that with all rooks present,
// doubled pawns "cost" only about 1/16th of a pawn on average.  With
// one rook each the cost rises to 1/4th of a pawn and with no rooks
// present to 3/8ths of a pawn.  With the queens present the cost is
// again only 1/16th of a pawn; without them it's a quarter pawn.  So
// the lessons are clear; beware of doubled pawns when major pieces
// have been exchanged, and beware of exchanging major pieces when you
// are the one with the doubled pawns."
//                                                --Larry Kaufman, IM
//                                          "All About Doubled Pawns"
//
// Note: indexed by number of files with 1+ pawn on them.
static SCORE DOUBLED_PAWN_PENALTY_BY_COUNT[4][9] =
{    // ------------ count of doubled+ pawns ------------
    {// 0    1     2     3      4     5     6     7     8 : no majors alive
      +0,  -32,  -65,  -99,  -134, -170, -207, -222, -250
    },
    {//                                                   : 1 rook
      +0,  -23,  -47,  -76,  -108, -144, -184, -200, -216
    },
    {//                                                   : 2 rooks or 1 queen
      +0,  -13,  -23,  -34,  -46,   -64,  -86, -111, -138
    },
    {//                                                   : all majors alive
      +0,   -7,  -13,  -25,  -39,   -55,  -73,  -95, -121
    },
};

static SCORE ISOLATED_PAWN_BY_PAWNFILE[9] =
{
    0, -8, -9, -10, -10, -10, -10, -9, -8
};

static SCORE ISOLATED_EXPOSED_PAWN = -5;

// Turned down (2026-08-30): a per-pawn modifier that stacks on top of
//< DOUBLED_PAWN_PENALTY_BY_COUNT's whole-position doubled-pawn aggregate
// for the specific case of a pawn that's both isolated and doubled --
// a different angle (single-worst-case flag vs. whole-position
// severity), not the same fact counted twice, so scaled down rather
// than removed.
static SCORE ISOLATED_DOUBLED_PAWN = -7;

//
// Note: -25% to -33% if the enemy occupies or controls the next sq.
//
static SCORE PASSER_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7    8
    { +0,  +0,+162,+111, +62, +36, +18, +13,  +0 }, // black
    { +0,  +0, +13, +18, +36, +62,+111,+162,  +0 }  // white
};

static SCORE CANDIDATE_PASSER_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7   8
    { +0,  +0,  +0, +48, +34, +22, +13,  +9,  +0 }, // black
    { +0,  +0,  +9, +13, +22, +34, +48,  +0,  +0 }  // white
};

// Note: x2
// Scaled to 1/3 of the original hand-tuned magnitude (2026-08-30): these
// three terms, plus PASSER_BY_RANK and OUTSIDE_PASSER_BY_DISTANCE, all
// separately price "how good is this passer" from different angles
// (connected to a partner passer, backed by an ordinary pawn, outside
// the opposing pawn majority) and can stack for the same pawn -- a
// rank-7 connected+outside passer could hit ~370cp in this pawn-hash-
// cached family alone, ~9x Crafty's ~40cp ceiling for the equivalent
// concept. Rather than remove any of these (they're each pricing a
// genuinely distinct structural fact, not re-counting the same one --
// and pawn-hash caching makes the compute cost of keeping all of them
// free), turned the magnitude down on the three secondary/modifier
// terms so the stack lands in a saner range; PASSER_BY_RANK (the core
// "how far advanced" signal) is left as the primary, least-reduced
// term.
static SCORE CONNECTED_PASSERS_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7   8
    { +0,  +0, +32, +25, +16,  +7,  +3,  +2,  +0 }, // black
    { +0,  +0,  +2,  +3,  +7, +16, +25, +32,  +0 }  // white
};

static SCORE SUPPORTED_PASSER_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7   8
    { +0,  +0, +20, +13,  +4,  +2,  +1,  +1,  +0 }, // black
    { +0,  +0,  +1,  +1,  +2,  +4, +13, +20,  +0 }  // white
};

// Split out 2026-08-30 from SUPPORTED_PASSER_BY_RANK, which _EvalKing's
// "kings in front of passers" endgame bonus was silently reusing --
// pawn-support and king-escort are different concepts (this fires when
// the KING stands next to its own passer, not when a pawn does), so
// scaling one for its real purpose was silently also scaling the
// other. Seeded with SUPPORTED_PASSER_BY_RANK's original (pre-scaling)
// hand-tuned magnitude, since that's what this use case was actually
// getting before today's pawn-hash pass touched the shared table for
// an unrelated reason.
static SCORE KING_SUPPORTING_OWN_PASSER_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7   8
    { +0,  +0, +60, +40, +13,  +6,  +3,  +1,  +0 }, // black
    { +0,  +0,  +1,  +3,  +6, +13, +40, +60,  +0 }  // white
};

static SCORE OUTSIDE_PASSER_BY_DISTANCE[9] =
{//    0    1    2    3    4    5    6    7    8
      +0,  +0,  +2,  +5,  +7,  +9, +11, +14, +18
};

static SCORE PASSER_BONUS_AS_MATERIAL_COMES_OFF[32] =
{
//  none    na      na      m       na      R       2m      na
    +60,    -1,     -1,    +37,    -1,     +43,    +19,    -1,

//  Rm      3m/Q    2R      R2m     4m/Qm   2Rm     R3m/QR  Q2m
    +14,    +9,    +20,    +4,     +3,     +3,      0,      0,

//  2R2m    R4m/QRm Q3m     2R3m/   QR2m    Q4m     2R4m/   QR3m
//                          Q2R                     Q2Rm
    0,      0,      0,      0,      0,      0,      0,      0,

//  na      Q2R2m   QR4m    na      Q2R3m   na      na      full
    0,      0,      0,      0,      0,      0,      0,      0,
};

// 2026-09-17: was +800 -- found via fuzzing that _RecognizeKPK stacks
// material balance and a flat 2*VALUE_PAWN on top of this before
// returning it as a hard recognizer bound (RECOGN_LOWER/UPPER), so a
// "winning" race claim could reach ~988 total even before considering
// whether the claim itself was right. Crafty's equivalent term
// (pawn_can_promote, evaluate.h) is a flat 525 and -- critically --
// only ever an additive eval nudge feeding real alpha-beta search,
// never a hard bound. Turned down to ~300/pawn regardless of that
// separate soundness fix (see the losing-side-has-no-pawns guard in
// _RecognizeKPK) since the two problems compound independently.
SCORE RACER_WINS_RACE = +300;

static SCORE UNDEVELOPED_MINORS_IN_OPENING[5] =
{//  0    1    2    3    4
     0,  -14, -18, -24, -30
};

//
// Bishop eval terms
// ---------------------------------------------------------------------------
//

//
// "The bishop pair has an average value of half a pawn (more when the
// opponent has no minor pieces to exchange for one of the bishops),
// enough to regard it as part of the material evaluation of the
// position, and enough to overwhelm most positional considerations.
// Moreover, this substantial bishop pair value holds up in all
// situations tested, regardless of what else is on the board...
//
// ...One rule which I often teach to students is that if you have the
// bishop pair, and your opponent's single bishop is a bad bishop
// (hemmed in by his own pawns), you already have full compensation
// for a pawn... Kasparov has said something similar...
//
// As noted before, the bishop pair is worth more with fewer pawns on
// the board. Aside from this factor, the half pawn value of the
// bishop pair is remarkably constant, applying even when there are no
// pieces on the board except two minors each."
//                                                 --Larry Kaufman, IM
//                                   "Evaluation of Material Imbalance"
static SCORE BISHOP_PAIR_BONUS = 30;

static SCORE STATIONARY_PAWN_ON_BISHOP_COLOR[128] =
{
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0,
      -4,   -6,   -7,   -7,   -7,   -7,   -6,   -4,    0,0,0,0,0,0,0,0,
      -6,   -7,   -9,   -8,   -8,   -9,   -7,   -6,    0,0,0,0,0,0,0,0,
      -7,   -8,  -10,  -11,  -11,  -10,   -8,   -7,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -7,   -8,  -10,  -11,  -11,  -10,   -8,   -7,    0,0,0,0,0,0,0,0,
      -6,   -7,   -9,   -8,   -8,   -9,   -7,   -6,    0,0,0,0,0,0,0,0,
      -4,   -6,   -7,   -7,   -7,   -7,   -6,   -4,    0,0,0,0,0,0,0,0,
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0
};

static SCORE TRANSIENT_PAWN_ON_BISHOP_COLOR[128] =
{
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0,
      -1,   -1,   -2,   -2,   -2,   -2,   -1,   -1,    0,0,0,0,0,0,0,0,
      -3,   -4,   -4,   -4,   -4,   -4,   -4,   -3,    0,0,0,0,0,0,0,0,
      -4,   -5,   -7,   -8,   -8,   -7,   -5,   -4,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -4,   -5,   -7,   -8,   -8,   -7,   -5,   -4,    0,0,0,0,0,0,0,0,
      -3,   -4,   -4,   -4,   -4,   -4,   -4,   -3,    0,0,0,0,0,0,0,0,
      -1,   -1,   -2,   -2,   -2,   -2,   -1,   -1,    0,0,0,0,0,0,0,0,
      +0,   +0,   +0,   +0,   +0,   +0,   +0,   +0,    0,0,0,0,0,0,0,0
};

//
// A bishop can move to between 0..13 squares.
//
static SCORE BISHOP_MOBILITY_BY_SQUARES[14] =
{//   0    1    2   3   4   5   6   7   8   9  10  11  12  13
    -22, -14, -10, -5, -1,  0, +1, +3, +4, +5, +6, +7, +8, +9
};//                    ^   |


//
// Pseudo-mobility: squares this bishop can "see" past a directly-attacked
// higher-value enemy piece (rook/queen/king) -- real positional pressure
// (the squares a capture or a moving-away enemy piece would open up), not
// real mobility (the bishop cannot actually move there this ply). No
// attempt to model whether the bishop itself is defended -- that's a
// search-shaped question (SEE/exchange-accurate, whose-move-is-it), not
// an eval one; see MOBILITY_BITBOARD_REWRITE.md. Deliberately smaller
// than BISHOP_MOBILITY_BY_SQUARES throughout.
//
static SCORE BISHOP_XRAY_MOBILITY_BY_SQUARES[9] =
{//  0   1   2   3   4   5   6   7   8
    +0, +1, +1, +2, +2, +3, +3, +4, +4
};


static SCORE BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING[9] =
{//  0    1    2    3    4    5    6    7    8
    +0, +33, +28, +18,  +8,  +4,  +0, -10, -16
};

//
// Knight eval terms
// ---------------------------------------------------------------------------
//
static SCORE KNIGHT_CENTRALITY_BONUS[128] =
{
     -12,   -8,   -8,   -8,   -8,   -8,   -8,  -12,    0,0,0,0,0,0,0,0,
      -8,   -2,   -2,    0,    0,   -2,   -2,   -8,    0,0,0,0,0,0,0,0,
      -8,   -2,   +4,   +5,   +5,   +4,   -2,   -8,    0,0,0,0,0,0,0,0,
      -8,   -2,   +5,   +8,   +8,   +5,   -2,   -8,    0,0,0,0,0,0,0,0,
//  -------------------------------------------------------------------
      -8,   -2,   +5,   +8,   +8,   +5,   -2,   -8,    0,0,0,0,0,0,0,0,
      -8,   -2,   +4,   +5,   +5,   +4,   -2,   -8,    0,0,0,0,0,0,0,0,
      -8,   -2,   -2,    0,    0,   -2,   -2,   -8,    0,0,0,0,0,0,0,0,
     -12,   -8,   -8,   -8,   -8,   -8,   -8,  -12,    0,0,0,0,0,0,0,0
};

static SCORE KNIGHT_KING_TROPISM_BONUS[9] =
{//    0    1    2    3    4    5    6    7    8
       0, +15, +12,  +9,  +4,  +0,  +0,  +0,  +0
};


static SCORE KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING[9] =
{//    0    1    2    3    4    5    6    7    8
      +0, +25, +19, +14,  +6,  +0,  +0,  +0,  +0
};

static SCORE KNIGHT_ON_INTERESTING_SQUARE_BY_RANK[2][9] =
{//    0    1    2    3    4    5    6    7    8
    { +0, +12, +11,  +9,  +6,  +3,  +0,  +0,  +0 }, // black
    { +0,  +0,  +0,  +0,  +3,  +6,  +9, +11, +12 }  // white
};

//
// A knight can move to between 0..8 squares
// -----------------------------------------
// 0 = supported enemy pawn
// 1 = unsupported enemy pawn, friend pawn, enemy B/N
//     enemy controlled empty sq.
// 2 = enemy >B, friend controlled empty sq, no one controlled empty sq
//
// Total: 16 mobility max
//
static SCORE KNIGHT_MOBILITY_BY_COUNT[9] =
{//   0    1   2   3   4   5   6   7   8
    -17, -10, -6,  0, +3, +5, +7, +8, +8
};//               ^   |

static SCORE KNIGHT_WITH_N_PAWNS_SUPPORTING[3] =
{
    +0, +4, +8
};

static SCORE KNIGHT_IN_CLOSED_POSITION[33] =
{//  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  2,  4,  6,  9, 11,
    12, 13, 15, 17, 19, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 27
//  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32
};

//
// Rook eval terms
// ---------------------------------------------------------------------------
//
// Simplified 2026-09-06 (board_representation/EVAL.md section 9): flat
// average bonus, not scaled by distance from the enemy king -- by direct
// instruction. Each was a [8]-by-distance table; these are that table's
// simple mean, rounded.
static SCORE ROOK_ON_FULL_OPEN = 18;
static SCORE ROOK_ON_HALF_OPEN_WITH_ENEMY = 9;
static SCORE ROOK_ON_HALF_OPEN_WITH_FRIEND = 10;

// Cache of the three constants above, indexed [friend pawn on file?]
// [enemy pawn on file?] so _EvalRook's hot path is a single array read
// instead of rebuilding a local array every call. Not `static const`
// -- the three source constants are DNA-tunable globals (plain mutable
// SCORE, not compile-time constants), so this has to be a plain
// mutable array, rebuilt by InitializeEval() whenever they change (startup,
// and after every `evaldna read`), not frozen at compile time.
static SCORE ROOK_FULL_HALF_OPEN_BONUS[2][2] = { { 16, 9 }, { 10, 0 } };

// Same treatment for the enemy/friend-passer-on-file bonuses -- was
// PASSER_BY_RANK[xColor][rank]/4 (enemy case) and a rank-scaled
// behind/leads-passer split (friend case, +1..+25 behind, -3..-22 in
// front); flat means of the meaningful (non-padding) entries.
static SCORE ROOK_WITH_ENEMY_PASSER = 17;
static SCORE ROOK_WITH_FRIEND_PASSER = 10;

// A rook on the 7th (White) or 2nd (Black) rank attacks along the
// enemy's back-ranks-minus-one, hitting undeveloped/unmoved pawns and
// cutting the enemy king off from that rank -- a small, classic bonus
// independent of the file-openness/passer bonuses above. BBRANK22/
// BBRANK77 are compile-time constants (chess.h), so this table (unlike
// ROOK_FULL_HALF_OPEN_BONUS above) can be a real `static const`: it
// depends on the board geometry, not on any DNA-tunable value.
static const BITBOARD BBROOK_7TH_RANK[2] = { BBRANK22, BBRANK77 }; // [BLACK], [WHITE]
static SCORE ROOK_ON_SEVENTH_BONUS = 9;

static SCORE ROOK_VALUE_AS_PAWNS_COME_OFF[17] =
{//   0    1    2    3    4    5    6    7    8
    +55, +51, +44, +38, +33, +27, +22, +16,  +7,
 //        9   10   11   12   13   14   15   16
          +1,  -3,  -6,  -9, -12, -18, -22, -25
};

//
// Note: these are multiplied by two (one per rook).
//
static SCORE ROOK_CONNECTED_VERT = +7;        // x2
static SCORE ROOK_CONNECTED_HORIZ = +4;       // x2

//
// A rook can move to between 0..14 squares
// ----------------------------------------
// 0 = supported enemy P/N/B, friend piece
// 1 = unsupported enemy piece, enemy controlled empty sq, enemy R
// 2 = enemy >R, friend controlled empty sq, no one controlled empty sq
//
// Total: 28 mobility max
//
static SCORE ROOK_MOBILITY_BY_SQUARES[15] =
{//   0    1    2    3    4   5   6   7   8    9   10   11   12   13   14
    -32, -26, -20, -14,  -7, -2, +0, +4, +8, +12, +15, +17, +19, +21, +22
};//                          ^   |


//
// Pseudo-mobility: squares this rook can "see" past a directly-attacked
// enemy queen or king -- same idea as BISHOP_XRAY_MOBILITY_BY_SQUARES
// above, same caveats (no defended/undefended modeling -- that's
// search's job). Deliberately smaller than ROOK_MOBILITY_BY_SQUARES
// throughout.
//
static SCORE ROOK_XRAY_MOBILITY_BY_SQUARES[9] =
{//  0   1   2   3   4   5   6   7   8
    +0, +1, +1, +2, +2, +3, +3, +4, +4
};


//
// Queen eval terms
// ---------------------------------------------------------------------------
//

//
// A queen can move to between 0..27 squares
// -----------------------------------------
// 0 = supported enemy P/N/B/R, friend piece
// 1 = unsupported enemy piece, enemy controlled empty sq, enemy Q
// 2 = enemy K, no one controlled empty sq, friend controlled empty sq
//
// Total: 54 mobility max
//
static SCORE QUEEN_MOBILITY_BY_SQUARES[28] =
{// 0    1    2    3    4     5   6    7    8   9  10  11   12   13   14
  -30, -26, -22, -17, -11,   -8, -4,  -2,  -1, +2, +4, +7, +10, +12, +14,
//                                            |

 //15   16   17   18   19   20   21   22   23   24   25   26   27
  +15, +16, +17, +18, +19, +20, +20, +21, +21, +22, +22, +23, +23
};

//
// In "Evaluation of Material Imbalance", IM Larry Kaufman makes the
// point that queens are worth more then the standard nine "points".
// Thus, this scale is biased upwards by about 0.15 pawn.
//
static SCORE QUEEN_KING_TROPISM[8] =
{// 0    1    2    3    4    5    6    7
    0, +34, +28, +22, +19, +17, +16, +15
};

//
// King eval terms
// ---------------------------------------------------------------------------
//
// 2026-09-15: this table is ONLY for CountKingSafetyDefects (the cheap
// lazy-eval-proxy/search-extension-reduction-gate sibling of _EvalKing,
// called directly from search.c/searchsup.c independent of Eval() ever
// running) -- deliberately frozen/split off from _EvalKing's own real
// computation (see KING_EVAL_INITIAL_LOCATION below), which used to
// read this exact array. That coupling meant any future retune of
// _EvalKing's king-location term would silently perturb search
// extension/reduction gate frequency too, an unrelated and much
// higher-blast-radius side effect than "retune an eval term" should
// have. DO NOT repoint _EvalKing at this table again -- add to/reshape
// KING_EVAL_INITIAL_LOCATION instead. See king_safety_data/HANDOFF.md's
// 2026-09-15 addendum.
static ULONG KING_INITIAL_COUNTER_BY_LOCATION[2][128] =
{
    {
           2,    0,    0,    0,    1,    0,    0,    2,    0,0,0,0,0,0,0,0,
           1,    1,    1,    1,    1,    1,    1,    1,    0,0,0,0,0,0,0,0,
           3,    3,    3,    3,    3,    3,    3,    3,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
    //  -------------------------------------------------------------------
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0
    },
    {
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
    //  -------------------------------------------------------------------
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           3,    3,    3,    3,    3,    3,    3,    3,    0,0,0,0,0,0,0,0,
           1,    1,    1,    1,    1,    1,    1,    1,    0,0,0,0,0,0,0,0,
           2,    0,    0,    0,    1,    0,    0,    2,    0,0,0,0,0,0,0,0
    }
};

// 2026-09-15: _EvalKing's own copy -- same starting values as
// KING_INITIAL_COUNTER_BY_LOCATION above (no retuning done yet, this
// split is purely about ownership/decoupling), but SCORE-typed (this
// function's real ring-scan is SCORE-native post-rewrite, no more
// shared uCounter) and free to be reshaped independently -- e.g. the
// offboard-ring-exposure idea from king_safety_data/HANDOFF.md's
// session notes (a1-style corner exposure, distinct from this table's
// current pure-rank shape) without touching CountKingSafetyDefects'
// search-gate behavior at all.
static SCORE KING_EVAL_INITIAL_LOCATION[2][128] =
{
    {
           2,    0,    0,    0,    1,    0,    0,    2,    0,0,0,0,0,0,0,0,
           3,    1,    1,    1,    1,    1,    1,    3,    0,0,0,0,0,0,0,0,
           4,    3,    3,    3,    3,    3,    3,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
    //  -------------------------------------------------------------------
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0
    },
    {
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
    //  -------------------------------------------------------------------
           4,    4,    4,    4,    4,    4,    4,    4,    0,0,0,0,0,0,0,0,
           4,    3,    3,    3,    3,    3,    3,    4,    0,0,0,0,0,0,0,0,
           3,    1,    1,    1,    1,    1,    1,    3,    0,0,0,0,0,0,0,0,
           2,    0,    0,    0,    1,    0,    0,    2,    0,0,0,0,0,0,0,0
    }
};

static SCORE KING_TO_CENTER[128] =
{
      +0,  +0,  +0,  +0,  +0,  +0,  +0,  +0,    0,0,0,0,0,0,0,0,
      +1,  +3,  +5,  +7,  +7,  +5,  +3,  +1,    0,0,0,0,0,0,0,0,
      +3,  +5, +13, +15, +15, +13,  +5,  +3,    0,0,0,0,0,0,0,0,
      +5,  +7, +17, +23, +23, +17,  +7,  +5,    0,0,0,0,0,0,0,0,
//  ------------------------------------------------------------------
      +5,  +7, +17, +23, +23, +17,  +7,  +5,    0,0,0,0,0,0,0,0,
      +3,  +5, +13, +15, +15, +13,  +5,  +3,    0,0,0,0,0,0,0,0,
      +1,  +3,  +5,  +7,  +7,  +5,  +3,  +1,    0,0,0,0,0,0,0,0,
      +0,  +0,  +0,  +0,  +0,  +0,  +0,  +0,    0,0,0,0,0,0,0,0
};

//
// If a side has less than this much material we don't bother scoring
// the other side's king safety.  Note: this doesn't incl pawn
// material.
//
// 2026-10-06: also now the single dividing line for _EvalKing's whole
// safety-vs-activity split (see that function's header comment) --
// below this, the king is actively encouraged out (KING_TO_CENTER)
// instead of just not being penalized for leaving. The separate,
// stricter KEEP_KING_AT_HOME_THRESHOLD used to gate the stay-home
// bonus on its own, independently of this one, leaving a dead band
// between the two thresholds where safety was scored but neither the
// stay-home bonus nor any come-out encouragement applied. Retired --
// the stay-home bonus now uses this same threshold, so "safety scored"
// and "stay-home bonus applies" are exactly the same condition.
#define DO_KING_SAFETY_THRESHOLD \
    (VALUE_ROOK + VALUE_BISHOP + VALUE_BISHOP + VALUE_KING)

static ULONG KING_COUNTER_BY_ATTACK_PATTERN[32] =
{
//p 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
//m 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
//r 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
//q 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
//k 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
    0,0,2,2,1,1,3,3,1,1,3,3,2,2,4,4,2,2,3,3,2,2,4,4,2,2,4,4,3,4,5,5
};

static SCORE KING_SAFETY_BY_COUNTER[42] =
{
      -0,  -4,  -8, -12, -16, -20, -25, -31, -38, -50, -63, -76, -90,
    -105,-120,-135,-150,-165,-180,-195,-210,-225,-240,-255,-270,-290,
    -310,-330,-350,-370,-390,-410,-440,-470,-500,-500,-500,-500,-500,
    -500,-500,-500
};

// Added 2026-08-30: penalty for the enemy queen directly attacking or
// x-raying squares near this king, indexed by count (capped at 6).
// Replaces the old per-queen "pointing near enemy K" bolt-on
// (QUEEN_ATTACKS_SQ_NEXT_TO_KING, computed via the queen's own
// mobility ray-cast, direct-attacks only) with a version computed from
// data this loop already reads for king safety (no extra attack-table
// work) and that also catches x-ray/latent queen threats the old
// version missed. Calibrated against the removed term's own magnitude
// (uNearKing * 8, capped at 6 -> max 48) rather than guessed, since
// that's what was empirically shown to matter for real solve rate --
// see the 180-position king-safety-term distribution sampled
// 2026-08-30 (median -27, p75 -16, only ~1% worse than -200) for the
// scale this needs to slot into.
// 2026-09-14: rescaled from the original -8/count step (see the
// 2026-08-30 comment above -- that step was calibrated against a
// *removed* legacy term's own magnitude, not against real mate data).
// king_safety_data/HANDOFF.md's mate-mining logistic regression found
// `queenproximity` (after folding in the collinear front/back/sq3/sq4
// atk_queen sub-features it was absorbing -- see
// eval_tune/king_safety_data/HANDOFF.md's 2026-09-14 addendum) has a
// per-unit raw coefficient of +1.00, calibrated against
// `misscastleshort`'s own cleaned coefficient (+0.71) and this table's
// sibling constant KING_MISSING_ONE_CASTLE_OPTION's already-live -23
// value (same direct-EVAL_TERM unit family, unlike the file-storm
// tables below which feed the separate uCounter/KING_SAFETY_BY_COUNTER
// lookup and need their own, different calibration) -- see
// (misscastleshort_live / misscastleshort_raw_coef) = k, then
// k * queenproximity_raw_coef =~ -32/count.
//
// -32/count self-play-tested net negative (2780 games, score 0.490,
// llr -1.91 trending to H0) alongside the back-flight bonus below --
// consistent with this term's own weaker calibration confidence flagged
// up front (anchored against misscastleshort's never-independently-
// validated historical value, a bigger single-step jump than the
// file-storm retune's already-large ~1.75-2x). Direction still looks
// right (a real, non-collinear predictor), so trimmed 33% to -21/count
// rather than reverted outright. Re-validate via sd10 + self-play
// before trusting this magnitude either.
// -21/count + material scaling (see above) pulled self-play from
// clearly negative (score 0.490, llr -1.91 unscaled) to nearly flat
// (770 games, score 0.494, llr -0.34, drifting slowly) -- scaling was
// the bigger fix, but still trending slightly negative. Trimmed
// another ~33% to -14/count.
static SCORE KING_QUEEN_PROXIMITY_DANGER[7] =
{//    0    1    2    3    4    5    6
     +0, -10, -18, -25, -32, -39, -55
};

static SCORE KING_MISSING_ONE_CASTLE_OPTION = -23;

// 2026-09-14: new term, not a retune of an existing one.
// king_safety_data/HANDOFF.md's regression found `back_flight` (an
// empty, unattacked ring square on the side of the king AWAY from the
// attacker) is a real, non-collinear PROTECTIVE signal (negative raw
// coefficient -0.035, i.e. more open escape squares behind the king
// predicts LESS mate risk) -- unlike `front_flight`, which is a real
// danger signal already captured by EmptyUnattackedSquare's front
// weight. Calibrated the same way as KING_QUEEN_PROXIMITY_DANGER above
// (misscastleshort-anchored k =~ -32.4, applied to back_flight's raw
// coefficient) =~ +1.1/square, originally rounded to +1 -- but that
// +1 was never independently self-play tested in isolation (the
// "worth landing and validating" below didn't happen before other
// king-safety changes piled on top of it), so it never carried the
// weight of a validated constant, just a first guess like everything
// else in this file.
//
// 2026-09-15: nudged +1 -> +3. Every regression refit run this session
// (the original mate-mining regression, and 6,890-row and 92,468-row
// ElasticNet/Ridge fits on curated mate/control data) puts
// back_flight's magnitude at roughly half of front_flight's
// (KING_RING_FRONT_FLIGHT_PENALTY, -6); the +1 baseline's ratio (1/6)
// was much smaller than that. Small and deliberately so -- this is
// the single most novel, least-collinear finding from the regression,
// worth landing and validating in isolation before combining with
// anything else.
static SCORE KING_BACK_FLIGHT_BONUS = 3;

// 2026-09-15: _EvalKing's linear-SCORE ring-scan terms, promoted here
// from local statics inside that function so they're DNA-registered
// (see g_EvalDNA below) and Texel-tunable -- see that promotion's
// comment in _EvalKing for why (hand-translating mate-mining
// regression coefficients into centipawns via a single assumed anchor
// constant was the likely source of this rewrite's self-play
// regression, not the underlying feature signal). Starting values are
// unchanged from the original hand-translated guesses; only their
// storage location/tunability changed here.
//
// 2026-09-15 (later same day): nudged, NOT re-derived from scratch --
// absolute-magnitude derivation (regression coefficient -> centipawns
// via a single anchor constant, then Texel coordinate descent on top of
// curated data) was tried and abandoned; every method produced huge,
// untrustworthy magnitude swings (see eval_tune/ king-safety session
// notes). What *did* replicate cleanly across the original mate-mining
// regression, a small-scale (6,890-row) and full-scale (92,468-row)
// ElasticNet/Ridge refit was the *relative ranking* between terms, so
// only reordering/small nudges within the existing scale are applied:
//   - MINOR: data unanimously ranks side ~ front > back in danger;
//     baseline had back rated *most* dangerous (backwards) -- permuted
//     the same three magnitudes rather than resizing them.
//   - ROOK: baseline's front > back > side already matched the data's
//     ranking untouched.
//   - PAWN: data ranks pawn-ring-attacks mid-tier (stronger than
//     back-tier piece attacks), baseline had it tied for smallest --
//     small bump.
//   - UNDEFENDED: baseline already had back as the largest magnitude,
//     matching the one sub-signal (back_undef) that was stable across
//     every fit -- left alone. front/side undefended-square counts were
//     the single most consistently weak/sign-unstable feature across
//     every regression run tried (zeroed by ElasticNet, near-zero and
//     sign-flipping under Ridge) -- softened slightly rather than left
//     implying confidence the data doesn't support.
//   - XRAY: consistently signed, non-trivial magnitude in every fit;
//     baseline had it smallest in the whole file -- small bump.
//   - FRONT_FLIGHT_PENALTY: already correctly signed/positioned once
//     PAWN moved above it -- untouched.
//   - BACK_FLIGHT_BONUS (see above): data puts this at roughly half of
//     FRONT_FLIGHT_PENALTY's magnitude; baseline's ratio was much
//     smaller than that -- small bump.
// KING_QUEEN_PROXIMITY_DANGER and KING_MISSING_ONE_CASTLE_OPTION
// deliberately NOT touched: the former is already self-play validated
// and not cleanly re-derivable at this feature granularity (a 7-bucket
// nonlinear table vs. one linear coefficient); the latter applies one
// shared constant to both short- and long-castle loss even though the
// regression finds those two nowhere near equally dangerous -- fixing
// that is a structural change (splitting the constant), not a nudge,
// and wasn't made without discussing it first.
//
// 2026-09-15 (later still): PAWN and XRAY nudged again after a THIRD,
// independent calibration method (logistic regression against material
// balance -- computed straight from the FEN via python-chess, not
// anything derived from these same ring features, so it doesn't have
// iSafety's circularity problem) confirmed the same finding as the
// first pass: both terms are still ranked mid/low here while every
// method tried puts them near the top tier, comparable to front-tier
// piece attacks. Rank order elsewhere (9 of 13 comparable terms)
// already matched this newest fit without further changes, including
// UNDEFENDED[back] and both flight terms -- only these two still
// disagreed, so only these two moved again.
static SCORE KING_RING_ATTACK_MINOR[3] = { -15, -14, -17 };
static SCORE KING_RING_ATTACK_ROOK[3]  = { -14, -11,  -8 };
static SCORE KING_RING_ATTACK_PAWN = -12;
static SCORE KING_RING_UNDEFENDED[3] = { -4, -12, -5 };
static SCORE KING_RING_XRAY_BONUS = -8;
static SCORE KING_RING_FRONT_FLIGHT_PENALTY = -6;
static SCORE KING_INITIAL_LOCATION_SCALE = -3;
static SCORE KING_ATTACK_PATTERN_SCALE = -10;
static SCORE KING_DANGER_ACCELERATOR[7] =
{//    0-55  56-111  112-167  168-223  224-279  280-335  336+
        128,    175,     225,     200,     145,     128,   128
};

// Flat "this is bad" flags for _EvalTrappedPieces -- not an attempt to
// price the material outcome (search resolves that), just a nudge away
// from positions with a piece that looks stuck. ENPRISE_AND_TRAPPED is
// larger because that case is opponent-to-move / imminently capturable;
// TRAPPED_WITH_MOVE is our own move, so there's still a chance to
// wriggle out.
static SCORE ENPRISE_AND_TRAPPED_PENALTY = -50;
static SCORE TRAPPED_WITH_MOVE_PENALTY = -10;

typedef struct _DNA_BASE_SIZE {
    SCORE *pBase;
    ULONG uCount;
} DNA_BASE_SIZE;

#define DNA_VAR(x)    {(SCORE *)&(x), 1}
#define DNA_ARRAY(x)  {(SCORE *)(x), ARRAY_LENGTH(x)}
#define DNA_MATRIX(x) {(SCORE *)(x), ARRAY_LENGTH(x) * ARRAY_LENGTH((x)[0])}
static DNA_BASE_SIZE g_EvalDNA[] = {
    DNA_ARRAY(REDUCED_MATERIAL_DOWN_SCALER),
    DNA_ARRAY(CASTLE_AND_DEVELOPMENT_SCALER),
    DNA_ARRAY(REDUCED_MATERIAL_UP_SCALER),
    DNA_ARRAY(PASSER_MATERIAL_UP_SCALER),
    DNA_ARRAY(PAWN_CENTRALITY_BONUS),
    DNA_ARRAY(BACKWARD_SHIELDED_BY_LOCATION),
    DNA_ARRAY(BACKWARD_EXPOSED_BY_LOCATION),
    DNA_MATRIX(DOUBLED_PAWN_PENALTY_BY_COUNT),
    DNA_ARRAY(ISOLATED_PAWN_BY_PAWNFILE),
    DNA_VAR(ISOLATED_EXPOSED_PAWN),
    DNA_VAR(ISOLATED_DOUBLED_PAWN),
    DNA_MATRIX(PASSER_BY_RANK),
    DNA_MATRIX(CANDIDATE_PASSER_BY_RANK),
    DNA_MATRIX(CONNECTED_PASSERS_BY_RANK),
    DNA_MATRIX(SUPPORTED_PASSER_BY_RANK),
    DNA_MATRIX(KING_SUPPORTING_OWN_PASSER_BY_RANK),
    DNA_ARRAY(OUTSIDE_PASSER_BY_DISTANCE),
    DNA_ARRAY(PASSER_BONUS_AS_MATERIAL_COMES_OFF),
    DNA_VAR(RACER_WINS_RACE),
    DNA_ARRAY(UNDEVELOPED_MINORS_IN_OPENING),
    DNA_VAR(BISHOP_PAIR_BONUS),
    DNA_ARRAY(STATIONARY_PAWN_ON_BISHOP_COLOR),
    DNA_ARRAY(TRANSIENT_PAWN_ON_BISHOP_COLOR),
    DNA_ARRAY(BISHOP_MOBILITY_BY_SQUARES),
    DNA_ARRAY(BISHOP_XRAY_MOBILITY_BY_SQUARES),
    DNA_ARRAY(BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING),
    DNA_ARRAY(KNIGHT_CENTRALITY_BONUS),
    DNA_ARRAY(KNIGHT_KING_TROPISM_BONUS),
    DNA_ARRAY(KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING),
    DNA_MATRIX(KNIGHT_ON_INTERESTING_SQUARE_BY_RANK),
    DNA_ARRAY(KNIGHT_MOBILITY_BY_COUNT),
    DNA_ARRAY(KNIGHT_WITH_N_PAWNS_SUPPORTING),
    DNA_ARRAY(KNIGHT_IN_CLOSED_POSITION),
    DNA_VAR(ROOK_ON_FULL_OPEN),
    DNA_VAR(ROOK_ON_HALF_OPEN_WITH_ENEMY),
    DNA_VAR(ROOK_ON_HALF_OPEN_WITH_FRIEND),
    DNA_VAR(ROOK_WITH_ENEMY_PASSER),
    DNA_VAR(ROOK_WITH_FRIEND_PASSER),
    DNA_VAR(ROOK_ON_SEVENTH_BONUS),
    DNA_ARRAY(ROOK_VALUE_AS_PAWNS_COME_OFF),
    DNA_VAR(ROOK_CONNECTED_VERT),
    DNA_VAR(ROOK_CONNECTED_HORIZ),
    DNA_ARRAY(ROOK_MOBILITY_BY_SQUARES),
    DNA_ARRAY(ROOK_XRAY_MOBILITY_BY_SQUARES),
    DNA_ARRAY(QUEEN_MOBILITY_BY_SQUARES),
    DNA_ARRAY(QUEEN_KING_TROPISM),
    DNA_MATRIX(KING_INITIAL_COUNTER_BY_LOCATION),
    DNA_MATRIX(KING_EVAL_INITIAL_LOCATION),
    DNA_ARRAY(KING_TO_CENTER),
    DNA_ARRAY(KING_SAFETY_BY_COUNTER),
    DNA_ARRAY(KING_QUEEN_PROXIMITY_DANGER),
    DNA_VAR(KING_MISSING_ONE_CASTLE_OPTION),
    DNA_VAR(KING_BACK_FLIGHT_BONUS),
    DNA_ARRAY(KING_RING_ATTACK_MINOR),
    DNA_ARRAY(KING_RING_ATTACK_ROOK),
    DNA_VAR(KING_RING_ATTACK_PAWN),
    DNA_ARRAY(KING_RING_UNDEFENDED),
    DNA_VAR(KING_RING_XRAY_BONUS),
    DNA_VAR(KING_RING_FRONT_FLIGHT_PENALTY),
    DNA_VAR(KING_INITIAL_LOCATION_SCALE),
    DNA_VAR(KING_ATTACK_PATTERN_SCALE),
    DNA_ARRAY(KING_DANGER_ACCELERATOR)
};

ULONG
DNABufferSizeBytes()
{
    ULONG u;
    ULONG uSize = 0;
    for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) {
        uSize += 10 * g_EvalDNA[u].uCount;
    }
    return uSize + 1;
}


char *
ExportEvalDNA()
{
    ULONG uSize = DNABufferSizeBytes();
    char *p = malloc(uSize);
    char *pch;
    ULONG u, v;
    SCORE *q;
    FLAG fFirst = TRUE;

    memset(p, 0, uSize);
    pch = p;
    for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) {
        q = g_EvalDNA[u].pBase;
        for (v = 0; v < g_EvalDNA[u].uCount; v++) {
            size_t cbLeft = uSize - (size_t)(pch - p);
            if (!fFirst) {
                pch += snprintf(pch, cbLeft, ",%d", *q);
            } else {
                pch += snprintf(pch, cbLeft, "%d", *q);
                fFirst = FALSE;
            }
            q++;
        }
        *pch++ = '\n';
        *pch = '\0';
        fFirst = TRUE;
    }
    return p; // caller must free
}

FLAG
WriteEvalDNA(char *szFilename)
{
    FILE *p = NULL;
    char *q = NULL;
    FLAG fRet = FALSE;

    if (SystemDoesFileExist(szFilename)) goto end;
    p = fopen(szFilename, "a+b");
    if (!p) goto end;
    q = ExportEvalDNA();
    if (!q) goto end;
    fprintf(p, "%s", q);
    fRet = TRUE;
 end:
    if (p) fclose(p);
    if (q) free(q);
    return fRet;
}

FLAG
ImportEvalDNA(char *p)
{
    ULONG u, v;

    for (u = 0; u < ARRAY_LENGTH(g_EvalDNA); u++) {
        for (v = 0; v < g_EvalDNA[u].uCount; v++) {
            while(*p && (!isdigit(*p) && (*p != '-'))) p++;
            if (*p == '\0') return FALSE;
            *(g_EvalDNA[u].pBase + v) = atoi(p);
            while(*p && (isdigit(*p) || (*p == '-'))) p++;
        }
    }
    return TRUE;
}

FLAG
ReadEvalDNA(char *szFilename)
{
    FILE *p = NULL;
    ULONG uSize = DNABufferSizeBytes();
    char *q = malloc(uSize);
    FLAG fRet = FALSE;
    static char line[1024];
    char *c;

    if (!q) goto end;
    memset(q, 0, uSize);
    p = fopen(szFilename, "rb");
    if (!p) {
        Trace("Failed to open file \"%s\"\n", szFilename);
        goto end;
    }
    while(fgets(line, 1024, p) != NULL) {
        c = strchr(line, '#');
        if (c) *c = '\0';
        c = line;
        strcat(q, c);
    }
    fRet = ImportEvalDNA(q);
 end:
    if (q) free(q);
    if (p) fclose(p);
    return fRet;
}



//
// Misc stuff
// ---------------------------------------------------------------------------
//

//
// The three ranks "around" a rank (indexed by rank, used in eval.c)
//
BITBOARD BBADJACENT_RANKS[9] =
{
    0,
    BBRANK11 | BBRANK22,
    BBRANK11 | BBRANK22 | BBRANK33,
    BBRANK22 | BBRANK33 | BBRANK44,
    BBRANK33 | BBRANK44 | BBRANK55,
    BBRANK44 | BBRANK55 | BBRANK66,
    BBRANK55 | BBRANK66 | BBRANK77,
    BBRANK66 | BBRANK77 | BBRANK88,
    BBRANK77 | BBRANK88
};


//
// The files "around" one, indexed by file (used in eval.c)
//
BITBOARD BBADJACENT_FILES[8] =
{
    // A = 0
    BBFILEB,

    // B = 1
    BBFILEA | BBFILEC,

    // C = 2
    BBFILEB | BBFILED,

    // D = 3
    BBFILEC | BBFILEE,

    // E = 4
    BBFILED | BBFILEF,

    // F = 5
    BBFILEE | BBFILEG,

    // G = 6
    BBFILEF | BBFILEH,

    // H = 7
    BBFILEG
};

//
// Same as BBADJACENT_FILES, but including the file itself -- callers
// that used to OR in BBFILE[file] separately at every call (only one
// site, eval.c's _EvalKing) can index this instead and skip the extra
// load + OR.
//
BITBOARD BBADJACENT_FILES_INCLUSIVE[8] =
{
    // A = 0
    BBFILEA | BBFILEB,

    // B = 1
    BBFILEA | BBFILEB | BBFILEC,

    // C = 2
    BBFILEB | BBFILEC | BBFILED,

    // D = 3
    BBFILEC | BBFILED | BBFILEE,

    // E = 4
    BBFILED | BBFILEE | BBFILEF,

    // F = 5
    BBFILEE | BBFILEF | BBFILEG,

    // G = 6
    BBFILEF | BBFILEG | BBFILEH,

    // H = 7
    BBFILEG | BBFILEH
};

//
// The ranks preceeding one, indexed by rank/color of pawn (used in
// eval.c)
//
BITBOARD BBPRECEEDING_RANKS[8][2] =
{
    //     BLACK                          WHITE
    //     -----                          -----
    { // 0 == RANK8
        BBRANK72,                         0
    },
    { // 1 == RANK7
        BBRANK62,                         0
    },
    { // 2 == RANK6
        BBRANK52,                         BBRANK77
    },
    { // 3 == RANK5
        BBRANK42,                         BBRANK67
    },
    { // 4 == RANK4
        BBRANK32,                         BBRANK57
    },
    { // 5 == RANK3
        BBRANK22,                         BBRANK47
    },
    { // 6 == RANK2
        0,                                BBRANK37
    },
    { // 7 == RANK1
        0,                                BBRANK27
    }
};


static FLAG
_IsSquareSafeFromEnemyPawn(IN POSITION *pos,
                           IN COOR c,
                           IN BITBOARD bb)
/**

Routine description:

    Determine if a piece in square c is "outposted".  A piece is
    outposted if no enemy pawns can advance to attack it / drive
    it away.

Parameters:

    POSITION *pos : the board
    COOR c : the square (must not be empty!)
    BITBOARD bb : the bitboard of pawns you want to consider

Return value:

    FLAG : TRUE if the piece is safe/outposted, FALSE otherwise

**/
{
    ULONG uColor = GET_COLOR(pos->rgSquare[c].pPiece);
    ULONG uFile, uRank;
#ifdef DEBUG
    COOR cSquare;
    PIECE p = pos->rgSquare[c].pPiece;
    BITBOARD dbb = bb;

    ASSERT(IS_ON_BOARD(c));
    ASSERT(p && (IS_BISHOP(p) || IS_KNIGHT(p) || IS_PAWN(p)));
    ASSERT(IS_VALID_COLOR(uColor));
#endif

    uFile = FILE(c);
    ASSERT(uFile < 8);
    bb &= BBADJACENT_FILES[uFile];

    ASSERT(((c & 0x70) >> 4) == (c >> 4));
    uRank = c >> 4;
    ASSERT(uRank < 8);
    bb &= BBPRECEEDING_RANKS[uRank][uColor];

#ifdef DEBUG
    if (bb != 0)
    {
        while(IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&dbb)))
        {
            ASSERT(pos->rgSquare[cSquare].pPiece);
            ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece));
            if ((FILE(cSquare) == (FILE(c) - 1)) ||
                (FILE(cSquare) == (FILE(c) + 1)))
            {
                switch(uColor)
                {
                    case WHITE:
                        if (RANK(cSquare) > RANK(c))
                        {
                            return(FALSE);
                        }
                        break;
                    case BLACK:
                        if (RANK(cSquare) < RANK(c))
                        {
                            return(FALSE);
                        }
                        break;
                }
            }
        }
        ASSERT(FALSE);
    }
    else
    {
        ASSERT(bb == 0);
        while(IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&dbb)))
        {
            ASSERT(pos->rgSquare[cSquare].pPiece);
            ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece));
            if ((FILE(cSquare) == (FILE(c) - 1)) ||
                (FILE(cSquare) == (FILE(c) + 1)))
            {
                switch(uColor)
                {
                    case WHITE:
                        if (RANK(cSquare) > RANK(c))
                        {
                            ASSERT(FALSE);
                        }
                        break;
                    case BLACK:
                        if (RANK(cSquare) < RANK(c))
                        {
                            ASSERT(FALSE);
                        }
                        break;
                }
            }
        }
    }
#endif
    return(bb == 0);
}


static ULONG
_WhoControlsSquareFast(IN POSITION *pos,
                       IN COOR c)
/**

Routine description:

    Determine which side controls a board square.

Parameters:

    POSITION *pos : the board
    COOR c : the square in question

Return value:

    static ULONG : (ULONG)-1 if neither side controls it or the sides
    control it evenly, WHITE if white controls the square, or BLACK if
    black controls the square.

**/
{
    //
    // board_representation/EVAL.md section 9: bvAttacks/ATTACK_BITV
    // retired entirely now that king (the last piece to write it) has
    // converted -- every side's presence at this square is read
    // straight off its own bbXAttacks accumulator instead. Bit
    // positions (PAWN_BIT/MINOR_BIT/ROOK_BIT/QUEEN_BIT/KING_BIT) are
    // unchanged so g_SwapTable's indexing below still sees the same
    // shape it always has; x-ray-only presence (bbMinorXrayAttacks/
    // bbRookXrayAttacks/bbQueenXrayAttacks) ORs into the same
    // byte-scale bit as its direct-attack counterpart, matching the
    // old struct's .uSmall/.uXray sharing one bit position for
    // "attacks or x-rays" (see g_SwapTable's own construction). King
    // has no x-ray (can't move through a blocker). This function is
    // only ever called after *both* kings finish evaluating (the
    // passed-pawn re-check and trapped-piece/danger passes all run
    // after Eval()'s king-eval block), so pos->bbKingAttacks is always
    // fully populated for both colors here -- unlike _EvalKing's own,
    // deliberately asymmetric internal bvAttack (see that function's
    // comment), this is a plain, symmetric fact query.
    //
    BITBOARD sq = COOR_TO_BB(c);
    ULONG uWhite = ((pos->bbPawnAttacks[WHITE] & sq) ? PAWN_BIT : 0) |
                   ((pos->bbMinorAttacks[WHITE] & sq) ? MINOR_BIT : 0) |
                   ((pos->bbMinorXrayAttacks[WHITE] & sq) ? MINOR_BIT : 0) |
                   ((pos->bbRookAttacks[WHITE] & sq) ? ROOK_BIT : 0) |
                   ((pos->bbRookXrayAttacks[WHITE] & sq) ? ROOK_BIT : 0) |
                   ((pos->bbQueenAttacks[WHITE] & sq) ? QUEEN_BIT : 0) |
                   ((pos->bbQueenXrayAttacks[WHITE] & sq) ? QUEEN_BIT : 0) |
                   ((pos->bbKingAttacks[WHITE] & sq) ? KING_BIT : 0);
    ULONG uBlack = ((pos->bbPawnAttacks[BLACK] & sq) ? PAWN_BIT : 0) |
                   ((pos->bbMinorAttacks[BLACK] & sq) ? MINOR_BIT : 0) |
                   ((pos->bbMinorXrayAttacks[BLACK] & sq) ? MINOR_BIT : 0) |
                   ((pos->bbRookAttacks[BLACK] & sq) ? ROOK_BIT : 0) |
                   ((pos->bbRookXrayAttacks[BLACK] & sq) ? ROOK_BIT : 0) |
                   ((pos->bbQueenAttacks[BLACK] & sq) ? QUEEN_BIT : 0) |
                   ((pos->bbQueenXrayAttacks[BLACK] & sq) ? QUEEN_BIT : 0) |
                   ((pos->bbKingAttacks[BLACK] & sq) ? KING_BIT : 0);
    ULONG u;
    PIECE p;
    CHAR ch;

    // g_SwapTable is only [14][32][32] (data.c) -- this is the bound
    // that actually matters, not just "no garbage above bit 7" below.
    // PAWN_BIT..KING_BIT briefly didn't fit in bits 0-4 earlier this
    // session (when _WhoControlsSquareFast was converted to read them
    // directly instead of going through the old ATTACK_BITV struct)
    // and silently indexed out of bounds on every attacked square --
    // the (& 0xFFFFFF00) checks below never caught it (board_
    // representation/EVAL.md section 9).
    ASSERT(uWhite < 32);
    ASSERT(uBlack < 32);
    ASSERT((uWhite & 0xFFFFFF00) == 0);
    ASSERT((uBlack & 0xFFFFFF00) == 0);

    p = pos->rgSquare[c].pPiece;
    ch = g_SwapTable[p][uWhite][uBlack];
    if (ch != 0)
    {
        u = ch;
        u >>= 7;
        u = u & 1;
        ASSERT(((u == 1) && (ch < 0)) ||
               ((u == 0) && (ch > 0)));
        return(FLIP(u));
    }
    return((ULONG)-1);
}

/**

Routine description:

    Zero out the Eval()-scoped attack-bitboard accumulators before
    building them for this call. Used to clear the old per-square
    rgSquare[c|8].bvAttacks/ATTACK_BITV structure too (a full-board
    macro-unrolled loop, since every square's storage needed zeroing);
    retired along with that structure (2026-09-05, board_
    representation/EVAL.md section 9) -- nothing left to clear but the
    bbXAttacks accumulators themselves.

Parameters:

    POSITION *pos

Return value:

    void

**/
static void
_ClearAttackTables(IN OUT POSITION *pos)
{
    pos->bbMinorAttacks[WHITE] = pos->bbMinorAttacks[BLACK] = 0;
    pos->bbMinorXrayAttacks[WHITE] = pos->bbMinorXrayAttacks[BLACK] = 0;
    pos->bbRookAttacks[WHITE] = pos->bbRookAttacks[BLACK] = 0;
    pos->bbRookXrayAttacks[WHITE] = pos->bbRookXrayAttacks[BLACK] = 0;
    pos->bbQueenAttacks[WHITE] = pos->bbQueenAttacks[BLACK] = 0;
    pos->bbQueenXrayAttacks[WHITE] = pos->bbQueenXrayAttacks[BLACK] = 0;
    pos->bbKingAttacks[WHITE] = pos->bbKingAttacks[BLACK] = 0;
}


static INLINE void
_InitializePawnHashEntry(IN OUT PAWN_HASH_ENTRY *pHash,
                         IN POSITION *pos)
/**

Routine description:

Parameters:

    PAWN_HASH_ENTRY *pHash,
    POSITION *pos

Return value:

    static INLINE void

**/
{
    memset(pHash, 0, sizeof(PAWN_HASH_ENTRY));
    pHash->u64Key = pos->u64PawnSig;
}


static INLINE void
_EvaluateCandidatePasser(IN POSITION *pos,
                         IN OUT PAWN_HASH_ENTRY *pHash,
                         IN COOR c)
/**

Routine description:

Parameters:

    POSITION *pos,
    PAWN_HASH_ENTRY *pHash,
    COOR c

Return value:

    static INLINE

**/
{
    COOR c1, cSquare;
    PIECE pSentry, pHelper;
    ULONG ucFile = FILE(c);
    ULONG uPawnFile = ucFile + 1;
    BITBOARD bb;
    ULONG uSentries, uHelpers;
    ULONG uColor;
    ULONG xColor;
    int d1;
#ifdef DEBUG
    COOR cVerifySquare;
    ULONG uVerifySentries;
#endif

    ASSERT(IS_ON_BOARD(c));
    ASSERT(RANK(c) >= 2);
    ASSERT(RANK(c) <= 7);
    pHelper = pos->rgSquare[c].pPiece;
    ASSERT(IS_PAWN(pHelper));
    uColor = GET_COLOR(pHelper);
    ASSERT(IS_VALID_COLOR(uColor));
    xColor = FLIP(uColor);

    // The only way a pawn can be a passer/candidate if the other
    // side has a pawn on its same file is if that enemy pawn is
    // behind it.  This is a corner case but it is important to
    // detect all passers.
    if (pHash->uCountPerFile[xColor][uPawnFile] != 0)
    {
        ASSERT((pos->bbPawns[xColor] & BBFILE[ucFile]) != 0);
        switch(uColor)
        {
            case WHITE:
                bb = pos->bbPawns[BLACK] & BBFILE[ucFile];
                ASSERT(bb);
                while(IS_ON_BOARD(c1 = CoorFromBitBoardRank8ToRank1(&bb)))
                {
                    ASSERT(FILE(c1) == ucFile);
                    if (c1 < c) return;
                }
                break;
            case BLACK:
                bb = pos->bbPawns[WHITE] & BBFILE[ucFile];
                ASSERT(bb);
                while(IS_ON_BOARD(c1 = CoorFromBitBoardRank1ToRank8(&bb)))
                {
                    ASSERT(FILE(c1) == ucFile);
                    if (c1 > c) return;
                }
                break;
        }
    }

    // Count xColor's sentry pawns and determine the location of the
    // critical square for the pawn at c to become a passer.  Note if
    // there are no sentries then this pawn (on square c) is a passer
    // already, not a candidate.
    bb = pos->bbPawns[xColor] & BBADJACENT_FILES[ucFile];
    bb &= BBPRECEEDING_RANKS[(c & 0x70) >> 4][uColor];
    if (!bb)
    {
        ASSERT(FastCountBits(bb) == 0);

        // There are no enemy sentries so this pawn is a passer.
        pHash->bbPasserLocations[uColor] |= COOR_TO_BB(c);
        ASSERT(FastCountBits(pHash->bbPasserLocations[uColor]) > 0);
        ASSERT(FastCountBits(pHash->bbPasserLocations[uColor]) <= 8);
        EVAL_TERM(uColor,
                  PAWN,
                  c,
                  pHash->iScore[uColor],
                  PASSER_BY_RANK[uColor][RANK(c)],
                  "passed pawn");

        // However, don't give doubled passers such a big bonus.
        if (IS_PAWN(pos->rgSquare[c - 16 * g_iAhead[uColor]].pPiece))
        {
            EVAL_TERM(uColor,
                      PAWN,
                      c,
                      pHash->iScore[uColor],
                      -(PASSER_BY_RANK[uColor][RANK(c)] / 2),
                      "doubled passer");
        }
        return;
    }
    uSentries = FastCountBits(bb);

    // There's one or more sentry pawns so we'll look for friendly
    // helpers to decide if this pawn is a candidate passer.  First
    // figure out the critical square we need to get the passer
    // through.
    //
    // Cheap short-circuit first: an advanced pawn (rank 6/7 for WHITE,
    // rank 2/3 for BLACK) with a friend pawn on either adjacent file
    // already qualifies as a candidate regardless of what the (far
    // more expensive) helper-square walk below would find -- the two
    // conditions are OR'd together at the bottom of this function, so
    // computing uHelpers when this is already true is pure wasted
    // work. Skip straight to the candidate-passer bonus in that case.
    //
    if ((pHash->uCountPerFile[uColor][uPawnFile + 1] +
         pHash->uCountPerFile[uColor][uPawnFile - 1]) &&
        (((WHITE == uColor) && (RANK(c) > 5)) ||
         ((BLACK == uColor) && (RANK(c) < 4))))
    {
        goto give_candidate_bonus;
    }

    if (uColor == WHITE)
    {
        pSentry = BLACK_PAWN;
        cSquare = CoorFromBitBoardRank1ToRank8(&bb);
        cSquare += 0x10;
    }
    else
    {
        pSentry = WHITE_PAWN;
        cSquare = CoorFromBitBoardRank8ToRank1(&bb);
        cSquare -= 0x10;
    }
    cSquare &= 0xF0;
    cSquare |= ucFile;
    ASSERT(IS_ON_BOARD(cSquare));
    ASSERT(FILE(cSquare) == ucFile);

#ifdef DEBUG
    uVerifySentries = 0;
    cVerifySquare = 0;
    d1 = 16 * g_iAhead[uColor];
    c1 = c + d1;
    do
    {
        if (IS_ON_BOARD(c1 - 1))
        {
            if (pos->rgSquare[c1 - 1].pPiece == pSentry)
            {
                uVerifySentries++;
                if (0 == cVerifySquare)
                {
                    cVerifySquare = c1 - d1;
                    ASSERT(cVerifySquare == cSquare);
                }
            }
        }
        if (IS_ON_BOARD(c1 + 1))
        {
            if (pos->rgSquare[c1 + 1].pPiece == pSentry)
            {
                uVerifySentries++;
                if (0 == cVerifySquare)
                {
                    cVerifySquare = c1 - d1;
                    ASSERT(cVerifySquare == cSquare);
                }
            }
        }
        c1 = c1 + d1;
    }
    while(!RANK8(c1) && !RANK1(c1));
    ASSERT(uVerifySentries == uSentries);
#endif

    //
    // Note: we don't do this with bitboards because we want to not
    // consider a pawn to be a potential passer if it can't safely
    // advance to get into helper position.
    //
    // IDEA: scale the candidate passer bonus based on rank AND on
    // the distance the helper(s) have to go to get into position.
    //
    // FIXED 2026-09-05 (found while removing rgSquare[c|8].bvAttacks
    // entirely, board_representation/EVAL.md section 9; landed as its
    // own change with its own before/after check, not bundled into
    // that mechanical cleanup commit). This function runs from
    // _EvalPawns, which is the *first* piece type evaluated each
    // Eval() call, so the only attack data that actually exists yet is
    // pos->bbPawnAttacks -- every non-pawn piece, and (since commit
    // 57502d6) pawns' own old bvAttacks write, happens later in the
    // same call. The original condition here read the old combined
    // bvAttacks word (all piece types), which had been silently
    // always-zero -- and this gate silently always-true -- since
    // 57502d6; narrowed to what's actually valid at this point:
    // pos->bbPawnAttacks only. This is narrower than the original
    // presumably intended (any piece type, not just pawns), but it's
    // a real, correct check instead of a fake one, and pawns are the
    // dominant real-world case for contesting a helper-pawn square
    // anyway.
    //
    uHelpers = 0;
    d1 = 16 * g_iAhead[uColor];
    ASSERT(-d1 == 16 * g_iBehind[uColor]);
    c1 = cSquare + 1 - d1;
    if ((IS_ON_BOARD(c1)) && (pHash->uCountPerFile[uColor][FILE(c1) + 1]))
    {
        ASSERT(pos->bbPawns[uColor] & BBFILE[FILE(c1)]);
        if (!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1)) ||
            (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1)))
        {
            // Friend helper pawn there?
            if (pos->rgSquare[c1].pPiece == pHelper)
            {
                uHelpers = 1;
                goto do_left;
            }

            // There is no helper pawn in the support position yet.
            // See if one can get there.
            c1 = c1 - d1;
            while (IS_ON_BOARD(c1) &&
                   ((!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1))) ||
                    (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1))))
            {
                if (pos->rgSquare[c1].pPiece == pHelper)
                {
                    uHelpers = 1;
                    break;
                }
                else if (pos->rgSquare[c1].pPiece == pSentry)
                {
                    break;
                }
                c1 = c1 - d1;
            }
        }
    }

 do_left:
    c1 = cSquare - 1 - d1;
    if ((IS_ON_BOARD(c1)) && (pHash->uCountPerFile[uColor][FILE(c1) + 1]))
    {
        ASSERT(pos->bbPawns[uColor] & BBFILE[FILE(c1)]);

        if (!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1)) ||
            (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1)))
        {
            // Already a helper there?
            if (pos->rgSquare[c1].pPiece == pHelper)
            {
                uHelpers++;
                goto done_helpers;
            }

            // There is no pawn in the left support position yet.  See
            // if one can get there.
            c1 -= d1;
            while (IS_ON_BOARD(c1) &&
                   ((!(pos->bbPawnAttacks[xColor] & COOR_TO_BB(c1))) ||
                    (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c1))))
            {
                if (pos->rgSquare[c1].pPiece == pHelper)
                {
                    uHelpers++;
                    break;
                }
                else if (pos->rgSquare[c1].pPiece == pSentry)
                {
                    break;
                }
                c1 -= d1;
            }
        }
    }

 done_helpers:
    if (uHelpers >= uSentries)
    {
 give_candidate_bonus:
        ASSERT(CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)] > 0);
        EVAL_TERM(uColor,
                  PAWN,
                  c,
                  pHash->iScore[uColor],
                  CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)],
                  "candidate passer");

        // If the other side has no pieces then give this candidate an
        // extra bonus -- used to be a second full copy of the same
        // CANDIDATE_PASSER_BY_RANK value (an exact duplicate of the
        // term just added above, not a different angle on it), now a
        // fractional modifier.
        if (TotalNonPawnCount(pos, xColor) == 1)
        {
            EVAL_TERM(uColor,
                      PAWN,
                      c,
                      pHash->iScore[uColor],
                      CANDIDATE_PASSER_BY_RANK[uColor][RANK(c)] / 2,
                      "candidate passer in endgame");
        }
    }
}

static void
_EvaluateConnectedSupportedOutsidePassers(IN POSITION *pos,
                                          IN OUT PAWN_HASH_ENTRY *pHash)
/**

Routine description:

Parameters:

    POSITION *pos,
    PAWN_HASH_ENTRY *pHash

Return value:

    void

**/
{
    ULONG uColor;
    ULONG xColor;
    ULONG u, v;
    COOR c;
    COOR cLeftmostPasser, cRightmostPasser;
    PIECE pFriend;
    COOR cSupport;
    BITBOARD bb;
    static const INT iDelta[5] =
    {
        -1, +1, +17, +15, 0
    };

    FOREACH_COLOR(uColor)
    {
        ASSERT(IS_VALID_COLOR(uColor));
        xColor = FLIP(uColor);
        if (pHash->bbPasserLocations[uColor])
        {
            ASSERT(FastCountBits(pos->bbPawns[uColor]) > 0);
            pFriend = BLACK_PAWN | uColor;
            cLeftmostPasser = cRightmostPasser = ILLEGAL_COOR;
            // Leftmost/rightmost is just a min/max over FILE(c) -- no
            // need to wrap the passer walk in an outer per-file loop
            // just to get a file-ordered traversal; a single flat walk
            // over the whole bbPasserLocations bitboard visits the same
            // squares (CoorFromBitBoardRank8ToRank1 pops in rank-major
            // order, so leftmost/rightmost has to be tracked by explicit
            // comparison either way, not by iteration order).
            bb = pHash->bbPasserLocations[uColor];
            while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb)))
            {
                ASSERT(pHash->uCountPerFile[uColor][FILE(c)+1] != 0);
                ASSERT(RANK(c) > 1);
                ASSERT(RANK(c) < 8);
                if ((cLeftmostPasser == ILLEGAL_COOR) ||
                    (FILE(c) < FILE(cLeftmostPasser)))
                {
                    cLeftmostPasser = c;
                }
                if ((cRightmostPasser == ILLEGAL_COOR) ||
                    (FILE(c) > FILE(cRightmostPasser)))
                {
                    cRightmostPasser = c;
                }

                v = 0;
                while(iDelta[v] != 0)
                {
                    cSupport = c + iDelta[v] * g_iBehind[uColor];
                    if (IS_ON_BOARD(cSupport))
                    {
                        if (pHash->bbPasserLocations[uColor] &
                            COOR_TO_BB(cSupport))
                        {
                            ASSERT(CONNECTED_PASSERS_BY_RANK[uColor]
                                   [RANK(c)] > 0);
                            EVAL_TERM(uColor,
                                      PAWN,
                                      c,
                                      pHash->iScore[uColor],
                                      CONNECTED_PASSERS_BY_RANK[uColor]
                                      [RANK(c)],
                                      "connected passers");

                            //
                            // TODO: connected passers vs a R is
                            // strong.
                            //
                        }
                        else if (pos->rgSquare[cSupport].pPiece ==
                                 pFriend)
                        {
                            ASSERT(SUPPORTED_PASSER_BY_RANK[uColor]
                                   [RANK(c)] > 0);
                            EVAL_TERM(uColor,
                                      PAWN,
                                      c,
                                      pHash->iScore[uColor],
                                      SUPPORTED_PASSER_BY_RANK[uColor]
                                      [RANK(c)],
                                      "supported passer");
                        }
                    }
                    v++;
                }
            }

#ifdef DEBUG
            ASSERT(IS_ON_BOARD(cLeftmostPasser));
            ASSERT(IS_ON_BOARD(cRightmostPasser));
            ASSERT(RANK(cLeftmostPasser) > 1);
            ASSERT(RANK(cRightmostPasser) > 1);
            ASSERT(RANK(cLeftmostPasser) < 8);
            ASSERT(RANK(cRightmostPasser) < 8);
            if (FastCountBits(pHash->bbPasserLocations[uColor]) == 1)
            {
                ASSERT(cLeftmostPasser == cRightmostPasser);
            }
#endif
            for (u = A; u <= D; u++)
            {
                if (pHash->uCountPerFile[xColor][u + 1] != 0)
                {
                    ASSERT(pos->bbPawns[xColor] & BBFILE[u]);
                    if (!(pHash->bbPasserLocations[xColor] & BBFILE[u]))
                    {
                        break;
                    }
                }
            }
            if (u > FILE(cLeftmostPasser))
            {
                EVAL_TERM(uColor,
                          PAWN,
                          ILLEGAL_COOR,
                          pHash->iScore[uColor],
                          OUTSIDE_PASSER_BY_DISTANCE[u-FILE(cLeftmostPasser)],
                          "left outside passer");
            }

            for (u = H; u >= E; u--)
            {
                if (pHash->uCountPerFile[xColor][u + 1] != 0)
                {
                    ASSERT(pos->bbPawns[xColor] & BBFILE[u]);
                    if (!(pHash->bbPasserLocations[xColor] & BBFILE[u]))
                    {
                        break;
                    }
                }
            }
            if (u < FILE(cRightmostPasser))
            {
                EVAL_TERM(uColor,
                          PAWN,
                          ILLEGAL_COOR,
                          pHash->iScore[uColor],
                          OUTSIDE_PASSER_BY_DISTANCE[FILE(cRightmostPasser)-u],
                          "right outside passer");
            }
        }
    }
}


// board_representation/EVAL.md section 2/0d: bitboard replacement for
// the old per-pawn mailbox delta+IS_ON_BOARD population this function
// used to do. pos->bbPawns[2] already has every pawn location
// (incrementally maintained, chess.h) with zero per-pawn iteration
// needed to query it -- the exact shift-and-mask technique
// generate.c's _GenerateAllPawnMovesBB already uses to bulk-generate a
// whole side's pawn captures (its bbCapLeft/bbCapRight, before being
// masked down to actual enemy-occupied squares) is exactly "every
// square this side's pawns attack" -- reused here verbatim, minus the
// enemy-occupancy mask, since attack-bit population doesn't care what
// (if anything) sits on the attacked square. See that function's
// header comment for the full square-numbering/shift-direction
// derivation (WHITE forward = bb >> 8, BLACK forward = bb << 8,
// diagonals need the *opposite* file excluded to prevent same-row
// wraparound) -- not repeated here.
//
// Unlike the old version, this does NOT write PAWN_BIT into the old
// rgSquare[c|8].bvAttacks/ATTACK_BITV mechanism (retired entirely as
// of 2026-09-05, once king -- the last piece writing it -- converted
// too) -- pos->bbPawnAttacks[2] (chess.h) is the single source of
// truth for "does a pawn attack this square", read directly by every
// consumer. _ClearAttackTables(pos) still needs to run here first, to
// zero the other bbXAttacks accumulators knight/bishop/rook/queen/king
// populate as they each evaluate.
static void
_PopulatePawnAttackBits(IN OUT POSITION *pos)
/**

Routine description:

    Populate the attack table with pawn bits.

Parameters:

    POSITION *pos : the board

Return value:

    void

**/
{
    _ClearAttackTables(pos);

    pos->bbPawnAttacks[BLACK] =
        ((pos->bbPawns[BLACK] & ~BBFILE[0]) << 7) |
        ((pos->bbPawns[BLACK] & ~BBFILE[7]) << 9);
    pos->bbPawnAttacks[WHITE] =
        ((pos->bbPawns[WHITE] & ~BBFILE[0]) >> 9) |
        ((pos->bbPawns[WHITE] & ~BBFILE[7]) >> 7);
}


static INLINE FLAG
_FileCanSupportPawn(IN POSITION *pos,
                     IN PAWN_HASH_ENTRY *pHash,
                     IN ULONG uColor,
                     IN ULONG uPawnFile,
                     IN COOR c,
                     IN BITBOARD bbBlockingRanks)
/**

Routine description:

    Can a friendly pawn on uPawnFile ever defend the pawn on square c
    -- either right now (already within defending range) or later
    (nothing permanently blocks it from advancing into range)?

    NOTE: on a doubled adjacent file, this only looks at whether *a*
    helper pawn on uPawnFile can reach c -- if the nearest one's only
    route there is an unsafe one-step push, this returns FALSE even
    though a second, more distant pawn on the same file might still
    reach c safely later. Rare (requires doubled pawns on the adjacent
    file specifically) and consistent with the rest of this function's
    approximate, snapshot-in-time nature.

Parameters:

    POSITION *pos
    PAWN_HASH_ENTRY *pHash
    ULONG uColor : color of the pawn on c (and of the potential helper)
    ULONG uPawnFile : the adjacent file to test (0-7)
    COOR c : the pawn being supported
    BITBOARD bbBlockingRanks : c's rank plus every rank behind it, from
        uColor's forward direction (see caller)

Return value:

    FLAG

**/
{
    ULONG xColor = FLIP(uColor);

    if (0 == pHash->uCountPerFile[uColor][uPawnFile + 1])
    {
        return FALSE;                 // no friendly pawn on that file at all
    }
    if (pos->bbPawns[uColor] & BBFILE[uPawnFile] & BBADJACENT_RANKS[RANK(c)])
    {
        return TRUE;                  // already defending
    }

    // A friendly pawn one step short of defending range would have to
    // push onto its destination square to get there. If a live enemy
    // pawn attacks that destination and no friendly pawn attack of
    // our own covers it too (pos->bbPawnAttacks[] is already
    // populated by _PopulatePawnAttackBits before either _EvalPawns
    // pass runs, so both are real, current facts, not a guess about
    // some future position), pushing there just loses the pawn for
    // nothing -- not a safe way to arrive as a defender. If we also
    // attack the destination, the push is at worst an even trade, so
    // it doesn't disqualify this file. WHITE pushes toward decreasing
    // bitboard index (see _PopulatePawnAttackBits), so a pawn one
    // push short of the defending band sits at (band << 8), and its
    // destination is (that square >> 8) -- i.e. the original band
    // itself; BLACK is mirrored.
    {
        BITBOARD bbOneStepShort = (uColor == WHITE) ?
            (BBADJACENT_RANKS[RANK(c)] << 8) :
            (BBADJACENT_RANKS[RANK(c)] >> 8);
        BITBOARD bbHelper = pos->bbPawns[uColor] & BBFILE[uPawnFile] & bbOneStepShort;
        if (bbHelper)
        {
            BITBOARD bbDestination = (uColor == WHITE) ?
                (bbHelper >> 8) : (bbHelper << 8);
            if ((bbDestination & pos->bbPawnAttacks[xColor]) &&
                !(bbDestination & pos->bbPawnAttacks[uColor]))
            {
                return FALSE;
            }
        }
    }

    // A friendly pawn is on the file but not yet close enough to
    // defend -- it can still march up and defend later, unless an
    // enemy pawn on this same file already sits at c's rank or behind
    // it (from our own forward direction), permanently blocking the
    // way.
    return (0 == (pos->bbPawns[xColor] & BBFILE[uPawnFile] & bbBlockingRanks));
}


static INLINE FLAG
_IsBackwardPawn(IN POSITION *pos,
                IN ULONG uColor,
                IN COOR c,
                IN COOR cSquare)
/**

Routine description:

    Is the pawn on square c "backward"?  See "Pawn Power in Chess"
    pp. 25-27.  The caller has already established the one condition
    that needs pos->bbPawnAttacks[]: the enemy, not a friendly pawn,
    controls c's stop square (cSquare). This checks the three
    remaining, independently-necessary conditions:

      1. cSquare isn't itself occupied by a pawn (either color) --
         otherwise this is a blocked/rammed pawn, not a backward one.
      2. c has advanced far enough for the classification to apply.
      3. Neither neighbor on an adjacent file, one rank ahead of c,
         is a friendly pawn -- i.e. our neighbors have already
         advanced past c, so they can no longer shield it. (0x88
         coordinates make cSquare +/- 1 safe to test directly:
         IS_ON_BOARD() catches the file-edge case for free, unlike a
         bitboard shift which would need explicit BBFILE[0]/BBFILE[7]
         masking.)

Parameters:

    POSITION *pos
    ULONG uColor : color of the pawn on c
    COOR c : the pawn being tested
    COOR cSquare : c's stop square (one square ahead of c)

Return value:

    FLAG

**/
{
    PIECE p;

    if (IS_PAWN(pos->rgSquare[cSquare].pPiece))
    {
        return FALSE;                 // stop square is blocked by a pawn
    }
    if (!(((WHITE == uColor) && (RANK(c) < 4)) ||
          ((BLACK == uColor) && (RANK(c) > 5))))
    {
        return FALSE;                 // not advanced enough yet
    }

    p = (BLACK_PAWN | uColor);        // uColor's own pawn, regardless of color
    return ((IS_ON_BOARD(cSquare - 1) && (pos->rgSquare[cSquare - 1].pPiece == p)) ||
            (IS_ON_BOARD(cSquare + 1) && (pos->rgSquare[cSquare + 1].pPiece == p)));
}


PAWN_HASH_ENTRY *
EvalPawns(IN OUT SEARCHER_THREAD_CONTEXT *ctx,
           OUT FLAG *pfDeferred)
/**

Routine description:

    Evaluate pawn structures; return a ptr to a pawn hash entry.

    Exposed (non-static) so testrecogn.c can build a real,
    fully-populated PAWN_HASH_ENTRY (bbPasserLocations included) to
    drive an EGTB cross-check of _EvalPasserRacesAgainstLoneKings --
    same rationale as SideHasWinningChances's own exposure above.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx : the searcher thread context

Return value:

    PAWN_HASH_ENTRY *

**/
{
    static ULONG uUnmovedRank[2] = { 0x10, 0x60 };
    POSITION *pos = &ctx->sPosition;
    PAWN_HASH_ENTRY *pHash;
    COOR c, cSquare;
    ULONG uIsolated[2];
    ULONG uDoubled[2];
    SCORE iDuos[2];
    ULONG u, uPawnFile;
    ULONG uColor;
    BITBOARD bb;
    BITBOARD bbBlockingRanks;
    int d1;
#ifdef DEBUG
    SCORE t;
#endif

    // Look up the hash entry for this position.
    INC(ctx->sCounters.pawnhash.u64Probes);
    pHash = PawnHashLookup(ctx);
    ASSERT(NULL != pHash);
    if (pHash->u64Key == pos->u64PawnSig)
    {
        *pfDeferred = TRUE;
        INC(ctx->sCounters.pawnhash.u64Hits);
        return(pHash);
    }

    // We need the attack table to evaluate the pawns... and we missed
    // the hash table so we have to populate it now.  Can't defer this
    // one.
    *pfDeferred = FALSE;
    _InitializePawnHashEntry(pHash, pos);
    _PopulatePawnAttackBits(pos);
    uIsolated[BLACK] = uIsolated[WHITE] = 0;
    uDoubled[BLACK] = uDoubled[WHITE] = 0;
    iDuos[BLACK] = iDuos[WHITE] = 0;

    // First pass -- everything here except the per-square centrality
    // bonus is a closed-form aggregate over pos->bbPawns[uColor]
    // (uCountPerFile, uNumUnmovedPawns, bbStationaryPawns/
    // uNumRammedPawns), so none of it needs a per-pawn mailbox walk;
    // only the centrality lookup genuinely needs one (it's a per-square
    // table, not summable any other way).
    BITBOARD bbAllPawns = pos->bbPawns[WHITE] | pos->bbPawns[BLACK];

    FOREACH_COLOR(uColor)
    {
        ASSERT(IS_VALID_COLOR(uColor));

        // Pre-count number of  pawns per file, unrolled.
        ASSERT(pHash->uCountPerFile[uColor][0] == 0);
        pHash->uCountPerFile[uColor][A + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[A]);
        pHash->uCountPerFile[uColor][B + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[B]);
        pHash->uCountPerFile[uColor][C + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[C]);
        pHash->uCountPerFile[uColor][D + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[D]);
        pHash->uCountPerFile[uColor][E + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[E]);
        pHash->uCountPerFile[uColor][F + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[F]);
        pHash->uCountPerFile[uColor][G + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[G]);
        pHash->uCountPerFile[uColor][H + 1] = FastCountBits(pos->bbPawns[uColor] & BBFILE[H]);
        ASSERT(pHash->uCountPerFile[uColor][9] == 0);

        // Count number of unmoved pawns.
        pHash->uNumUnmovedPawns[uColor] = FastCountBits(pos->bbPawns[uColor] &
                                                    BBRANK[RANK(uUnmovedRank[uColor])]);
        ASSERT(pHash->uNumUnmovedPawns[uColor] <= 8);

        // Detect rammed and other stationary pawns. A pawn is
        // "stationary" if *any* pawn (either color -- e.g. a doubled
        // own-pawn block counts too) sits on its "stop square".  It's
        // specifically "rammed" only when that blocker is the
        // enemy's. WHITE's stop square is one rank toward rank8 (bit
        // index -8 in the linear 0-63 bitboard numbering -- see
        // _PopulatePawnAttackBits' >>8/<<8 shifts for the same
        // convention), BLACK's is +8.
        pHash->bbStationaryPawns[uColor] =
            (uColor == WHITE) ?
            (pos->bbPawns[WHITE] & (bbAllPawns << 8)) :
            (pos->bbPawns[BLACK] & (bbAllPawns >> 8));
        ASSERT(FastCountBits(pHash->bbStationaryPawns[uColor]) <= 8);

        // Give central pawns a small bonus and rook pawns a small
        // penalty.
        bb = pos->bbPawns[uColor];
        while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb)))
        {
            EVAL_TERM(uColor,
                      PAWN,
                      c,
                      pHash->iScore[uColor],
                      PAWN_CENTRALITY_BONUS[c],
                      "location");
        }
    }

    // Rammed pairs (an enemy pawn, not just any pawn, on the stop
    // square): each pair shows up as exactly one bit in each
    // side's own stationary-pawn count, so no double-counting
    // (and no /2 fixup) is needed the way the old per-pawn,
    // per-color loop required.
    pHash->uNumRammedPawns =
        FastCountBits(pos->bbPawns[WHITE] & (pos->bbPawns[BLACK] << 8));
    ASSERT(pHash->uNumRammedPawns <= 8);

    pHash->uTotalPawnCount = (UCHAR)FastCountBits(bbAllPawns);
    ASSERT(pHash->uTotalPawnCount <= 16);

    // _EvalKnight's closed-position scaler, computed once per unique
    // pawn structure instead of once per Eval() call -- see this
    // field's comment in chess.h.
    pHash->uClosedScaler = (UCHAR)(pHash->uTotalPawnCount -
        (pHash->uNumUnmovedPawns[WHITE] + pHash->uNumUnmovedPawns[BLACK]) +
        pHash->uNumRammedPawns);
    ASSERT(pHash->uClosedScaler <= 32);

    // Good/bad bishop pawn-structure score, cached per (color, color-
    // complex) instead of rescanned by every bishop of that color/
    // complex in _EvalBishop (board_representation/EVAL.md-style note:
    // every input here -- bbStationaryPawns, bbPawns, bbPawnAttacks --
    // is pure pawn-structure data already keyed by this pawn-hash
    // entry's signature, and the bishop's own square only ever selects
    // *which* of these two precomputed totals to use, never feeds the
    // computation itself. Semantics (corrected from the old per-bishop
    // version, which silently ignored enemy stationary pawns on the
    // bishop's complex entirely):
    //   - own stationary pawns on the complex: always count (full
    //     weight) -- they're not moving, they wall the bishop in for
    //     good.
    //   - enemy stationary pawns on the complex: count (full weight)
    //     only if defended by another enemy pawn -- an undefended
    //     stationary pawn is still a static target, not a durable
    //     obstruction, the same reasoning the transient case below
    //     already applied to enemy pawns.
    //   - own transient (non-stationary) pawns on the complex: always
    //     count (full weight) -- might move off later, hence the
    //     separate, lighter table.
    //   - enemy transient pawns on the complex: count (half weight)
    //     only if defended -- unsupported ones are likely to be traded
    //     off soon, not a durable obstruction.
    {
        static const BITBOARD bbColorSq[2] = { 0x55aa55aa55aa55aaULL,
                                               0xaa55aa55aa55aa55ULL };
        ULONG uComplex;

        FOREACH_COLOR(uColor)
        {
            ULONG xColor = FLIP(uColor);
            BITBOARD bbNonStationary = ~(pHash->bbStationaryPawns[WHITE] |
                                         pHash->bbStationaryPawns[BLACK]);

            for (uComplex = 0; uComplex < 2; uComplex++)
            {
                BITBOARD bbMask = bbColorSq[uComplex];
                SCORE i = 16;
                BITBOARD bb;
                COOR cSq;

                bb = pHash->bbStationaryPawns[uColor] & bbMask;
                while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb)))
                {
                    i += STATIONARY_PAWN_ON_BISHOP_COLOR[cSq];
                }

                bb = pHash->bbStationaryPawns[xColor] & bbMask;
                while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb)))
                {
                    if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSq))
                    {
                        i += STATIONARY_PAWN_ON_BISHOP_COLOR[cSq];
                    }
                }

                bb = pos->bbPawns[uColor] & bbNonStationary & bbMask;
                while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb)))
                {
                    i += TRANSIENT_PAWN_ON_BISHOP_COLOR[cSq];
                }

                bb = pos->bbPawns[xColor] & bbNonStationary & bbMask;
                while (IS_ON_BOARD(cSq = CoorFromBitBoardRank8ToRank1(&bb)))
                {
                    if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSq))
                    {
                        i += TRANSIENT_PAWN_ON_BISHOP_COLOR[cSq] / 2;
                    }
                }

                pHash->iBishopColorScore[uColor][uComplex] = (SHORT)i;
            }
        }
    }

    // Second pass, requires pHash->uCountPerFile[] populated for both
    // colors.
    FOREACH_COLOR(uColor)
    {
        ASSERT(IS_VALID_COLOR(uColor));
        ULONG xColor = FLIP(uColor);
        ASSERT(IS_VALID_COLOR(xColor));
        ASSERT(FastCountBits(pos->bbPawns[uColor]) <= 8);

        d1 = 16 * g_iAhead[uColor];
        BITBOARD bbPawnsToWalk = pos->bbPawns[uColor];

        while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bbPawnsToWalk)))
        {
            ASSERT(IS_PAWN(pos->rgSquare[c].pPiece));
            ASSERT((1 < RANK(c)) && (RANK(c) < 8));

            // Find weak pawns... pawns that are isolated are weak as
            // are pawns that have advanced beyond their support.
            // Both of these can tie up one or more pieces in order to
            // defend them. A pawn is a target unless a friendly pawn
            // on *either* adjacent file can defend it, now or later
            // (see _FileCanSupportPawn). bbBlockingRanks is c's rank
            // plus every rank behind it (from uColor's forward
            // direction) -- an enemy pawn there on an adjacent file
            // permanently blocks that file from ever producing a
            // defender.
            bbBlockingRanks = BBRANK[RANK(c)] | BBPRECEEDING_RANKS[c >> 4][uColor];
            if (!_FileCanSupportPawn(pos, pHash, uColor, FILE(c) - 1, c, bbBlockingRanks) &&
                !_FileCanSupportPawn(pos, pHash, uColor, FILE(c) + 1, c, bbBlockingRanks))
            {
                //
                // Single consolidated isolated-pawn penalty: base
                // severity by file, plus modifiers if the pawn is also
                // exposed and/or doubled. These used to be three
                // separate additive EVAL_TERM calls that all fired for
                // the same pawn, plus a fourth, whole-position
                // "exponential isolated" aggregate below that
                // double-counted the same uIsolated[] count this loop
                // already prices in one pawn at a time -- that
                // aggregate is removed entirely below rather than just
                // consolidated (see the comment there).
                //
                uPawnFile = FILE(c) + 1;
                uIsolated[uColor] += 1;
                ASSERT(uIsolated[uColor] > 0);
                ASSERT(uIsolated[uColor] <= 8);
                EVAL_TERM(uColor,
                          PAWN,
                          c,
                          pHash->iScore[uColor],
                          (ISOLATED_PAWN_BY_PAWNFILE[uPawnFile] +
                           ((pHash->uCountPerFile[xColor][uPawnFile]==0) *
                            ISOLATED_EXPOSED_PAWN) +
                           ((pHash->uCountPerFile[uColor][uPawnFile] > 1) *
                            ISOLATED_DOUBLED_PAWN)),
                          "isolated pawn");
            }

            uPawnFile = FILE(c) + 1;
            ASSERT((1 <= uPawnFile) && (uPawnFile <= 8));
            ASSERT(FastCountBits(pos->bbPawns[uColor] & BBFILE[FILE(c)])
                   == pHash->uCountPerFile[uColor][uPawnFile]);

            //
            // Keep count of doubled pawns
            //
            uDoubled[uColor] += (pHash->uCountPerFile[uColor][uPawnFile] > 1);
            ASSERT((0 <= uDoubled[uColor]) && (uDoubled[uColor] <= 8));

            //
            // We can detect pawn duos (triads, etc...) and backward pawns
            // by considering the control of the pawn's stopsquare.
            //
            cSquare = c + d1;
            ASSERT(IS_ON_BOARD(cSquare));
            //
            // At this point in Eval()'s sequence (inside _EvalPawns,
            // before any other piece type has run this call), pawns
            // are the only thing that could possibly have marked an
            // attack -- bvAttacks itself no longer carries the pawn
            // bit at all (see _PopulatePawnAttackBits), so this reads
            // pos->bbPawnAttacks directly instead of the (permanently
            // zero, at this point in execution) bvAttacks word.
            //
            if (pos->bbPawnAttacks[uColor] & COOR_TO_BB(cSquare))
            {
                //
                // Count pawn duos.  See "Pawn Power in Chess" pp 10-16
                //
#ifdef DEBUG
                t = ((uColor * RANK(cSquare)) +
                     (xColor * (9 - RANK(cSquare))));
                if (uColor == WHITE)
                {
                    ASSERT(t == RANK(cSquare));
                }
                else
                {
                    ASSERT(uColor == BLACK);
                    ASSERT(t == (9 - RANK(cSquare)));
                }
#endif
                iDuos[uColor] += ((uColor * RANK(cSquare)) +
                                  (xColor * (9 - RANK(cSquare))));
                ASSERT(iDuos[uColor] <= (7 * 8));
            }
            else if (pos->bbPawnAttacks[xColor] & COOR_TO_BB(cSquare))
            {
                //
                // Detect backwards pawns.  See "Pawn Power in Chess" pp 25-27
                //
                if (_IsBackwardPawn(pos, uColor, c, cSquare))
                {
                    //
                    // The pawn at c is backward.  Determine whether
                    // it is shielded or exposed.
                    //
                    pHash->bbStationaryPawns[uColor] |= COOR_TO_BB(c);
                    ASSERT(FastCountBits(pHash->bbStationaryPawns[uColor]) <= 8);
                    if (pHash->uCountPerFile[xColor][uPawnFile])
                    {
                        ASSERT(BACKWARD_SHIELDED_BY_LOCATION[c] < 0);
                        EVAL_TERM(uColor,
                                  PAWN,
                                  c,
                                  pHash->iScore[uColor],
                                  BACKWARD_SHIELDED_BY_LOCATION[c],
                                  "shielded backward pawn");
                    }
                    else
                    {
                        ASSERT(BACKWARD_EXPOSED_BY_LOCATION[c] < 0);
                        EVAL_TERM(uColor,
                                  PAWN,
                                  c,
                                  pHash->iScore[uColor],
                                  BACKWARD_EXPOSED_BY_LOCATION[c],
                                  "exposed backward pawn");
                    }
                }
                //
                // TODO: Think about backward doubled pawns; read Kauffman's
                // paper "All About Doubled Pawns".
                //
            }

            //
            // Handle passers / candidate passers
            //
            _EvaluateCandidatePasser(pos, pHash, c);
        }
    }

    //
    // Reward pawn duos, see "Pawn Power in Chess" pp. 10-16
    //
    ASSERT(iDuos[WHITE] >= 0);
    ASSERT(iDuos[WHITE] <= 56);
    ASSERT(iDuos[BLACK] >= 0);
    ASSERT(iDuos[BLACK] <= 56);
    EVAL_TERM(WHITE,
              PAWN,
              ILLEGAL_COOR,
              pHash->iScore[WHITE],
              iDuos[WHITE] / 2,
              "pawn duos");
    EVAL_TERM(BLACK,
              PAWN,
              ILLEGAL_COOR,
              pHash->iScore[BLACK],
              iDuos[BLACK] / 2,
              "pawn duos");

    //
    // The penalty for doubled pawns is scaled based on two primary
    // factors: the presence of major pieces for the side with doubled
    // pawns and the number of doubled pawns on the board.  The
    // presence of major pieces makes the doubled pawns less severe
    // while the presence of many doubled pawns makes the penalty for
    // each more severe.
    //
    ASSERT((uDoubled[WHITE] >= 0) && (uDoubled[WHITE] <= 8));
    ASSERT((uDoubled[BLACK] >= 0) && (uDoubled[BLACK] <= 8));
    u = FastCountBits(pos->bbPieces[BLACK][ROOK]) + FastCountBits(pos->bbPieces[BLACK][QUEEN]) * 2;
    u = MINU(u, 3);
    EVAL_TERM(BLACK,
              PAWN,
              ILLEGAL_COOR,
              pHash->iScore[BLACK],
              DOUBLED_PAWN_PENALTY_BY_COUNT[u][uDoubled[BLACK]],
              "exponential doubled");
    u = FastCountBits(pos->bbPieces[WHITE][ROOK]) + FastCountBits(pos->bbPieces[WHITE][QUEEN]) * 2;
    u = MINU(u, 3);
    EVAL_TERM(WHITE,
              PAWN,
              ILLEGAL_COOR,
              pHash->iScore[WHITE],
              DOUBLED_PAWN_PENALTY_BY_COUNT[u][uDoubled[WHITE]],
              "exponential doubled");

    ASSERT(uIsolated[WHITE] >= 0);
    ASSERT(uIsolated[WHITE] <= 8);
    ASSERT(uIsolated[BLACK] >= 0);
    ASSERT(uIsolated[BLACK] <= 8);

    //
    // Look for connected, supported and outside passed pawns to give
    // extra bonuses.
    //
    _EvaluateConnectedSupportedOutsidePassers(pos, pHash);

    //
    // TODO: recognize quartgrips and stonewalls
    //
    return(pHash);
}


ULONG
CountKingSafetyDefects(IN OUT POSITION *pos,
                       IN ULONG uColor)
/**

Routine description:

    Determine how many defects uColor's king position has _quickly_.
    TODO: add more knowledge as cheaply as possible...

Parameters:

    POSITION *pos,
    ULONG uColor

Return value:

    ULONG

**/
{
    ULONG uCounter = 0;
    ULONG xColor = FLIP(uColor);
    COOR cKing;
    BITBOARD bbKingZone;
    BITBOARD bbBlockers;
    BITBOARD bb;
    COOR c;

    //
    // Don't count king safety defects if the real eval code in
    // _EvalKing would not...
    //
    if (pos->uNonPawnMaterial[xColor] < DO_KING_SAFETY_THRESHOLD) {
        return 0;
    }

    cKing = KingPosition(pos, uColor);
    uCounter = KING_INITIAL_COUNTER_BY_LOCATION[uColor][cKing] >> 1;
    ASSERT(IS_KING(pos->rgSquare[cKing].pPiece));
    ASSERT(IS_ON_BOARD(cKing));
    ASSERT(GET_COLOR(pos->rgSquare[cKing].pPiece) == uColor);

    //
    // board_representation/EVAL.md section 9 follow-up (2026-09-05):
    // real, blocker-aware attack tests against the king's actual
    // 8-neighbor zone (the same zone _EvalKing's own KingSafetyDeltas
    // loop tests, now that its own bug -- testing 11 squares including
    // two bogus same-rank-2-away entries -- is fixed), replacing the
    // old CHECK_VECTOR_WITH_INDEX geometry-only lookup. That lookup
    // tested three hypothetical king positions (cKing-1, cKing,
    // cKing+1 -- always on the same rank, driven by CHECK_VECTOR's
    // one-dimensional index arithmetic) via a table with no board-
    // occupancy awareness at all -- it couldn't tell a rook on an open
    // file from one blocked by its own pawn, and never tested whether
    // a piece threatened a square one rank away from the king. This
    // version can't reuse pos->bbXAttacks (Eval()-scoped, and this
    // function is also called directly from search.c/searchsup.c as
    // an extension/reduction gate, independent of whether Eval() ran
    // on the current position at all) -- but pos->bbOccupied is a
    // real, always-current POSITION field regardless, so a fresh,
    // per-piece magic-bitboard lookup here is both cheap (same O(1)
    // shape as the old table lookups) and genuinely blocker-aware.
    // X-rays deliberately not considered via chain-following (that
    // would double the per-slider cost of a function called at every
    // lazy-eval check across the whole search tree, for what's already
    // a rough magnitude estimate, not an exact score) -- but the
    // occupancy fed to the slider lookups below is deliberately just
    // xColor's own pieces (_BuildFriendlySideBB(pos, xColor)), not the
    // whole board: a piece belonging to uColor (a defending pawn, the
    // king itself) is transparent to these rays, only xColor's own
    // pieces actually block. This gets latent-threat detection (a
    // rook aimed at the king zone but currently shielded by the
    // king's own pawn still counts) for free, at zero extra cost --
    // still one magic lookup per slider, just against a different
    // occupancy bitboard -- by direct instruction: we don't count our
    // own pieces as blocking the enemy king.
    //
    bbKingZone = g_KingAttacksBB[cKing] | COOR_TO_BB(cKing);
    bbBlockers = _BuildFriendlySideBB(pos, xColor);

    bb = pos->bbPieces[xColor][KNIGHT];
    while (bb)
    {
        c = CoorFromBitBoardRank8ToRank1(&bb);
        uCounter += (g_KnightAttacksBB[c] & bbKingZone) != 0;
    }
    bb = pos->bbPieces[xColor][BISHOP];
    while (bb)
    {
        c = CoorFromBitBoardRank8ToRank1(&bb);
        uCounter += (_BishopAttacksBB(c, bbBlockers) & bbKingZone) != 0;
    }
    bb = pos->bbPieces[xColor][ROOK];
    while (bb)
    {
        c = CoorFromBitBoardRank8ToRank1(&bb);
        uCounter += (_RookAttacksBB(c, bbBlockers) & bbKingZone) != 0;
    }
    // Queen hits count double -- by direct instruction: a queen near
    // the king is a real, distinct danger source _EvalKing's own
    // KING_QUEEN_PROXIMITY_DANGER term prices separately from generic
    // attack presence, and this counter had no way to reflect that
    // (a queen hitting the zone counted exactly the same as a lone
    // knight doing so). Raises the bound below accordingly (up to 8
    // queens are legal via promotion, each now worth 2).
    bb = pos->bbPieces[xColor][QUEEN];
    while (bb)
    {
        c = CoorFromBitBoardRank8ToRank1(&bb);
        uCounter += 2 * (((_RookAttacksBB(c, bbBlockers) |
                           _BishopAttacksBB(c, bbBlockers)) & bbKingZone) != 0);
    }
    ASSERT(uCounter < 30);

    return uCounter;
}


static SCORE
_ComputeFileStormDefects(IN POSITION *pos,
                         IN const PAWN_HASH_ENTRY *pHash,
                         IN ULONG uColor)
/**

Routine description:

    Real, exact open-file/storming-pawn defect count for uColor's
    king -- king's own file plus the two adjacent ones (2026-08-30:
    collapsed from three copy-pasted blocks that differed only in
    c-1/c/c+1). Extracted unchanged from _EvalKing (2026-09-05,
    board_representation/EVAL.md section 9's king-safety-hash
    prototype) so it can be called once per side from
    _GetFileStormDefects's cache-miss path instead of inline.

    2026-09-15: converted from an unsigned "counter" (fed through the
    old shared uCounter/KING_SAFETY_BY_COUNTER lookup) to a direct
    signed SCORE (centipawns), part of _EvalKing's move away from that
    shared nonlinear counter entirely -- see king_safety_data/
    HANDOFF.md's 2026-09-15 addendum. Table SHAPE below is the
    ORIGINAL, pre-2026-09-14 relative weighting (0,4,3,1,.../+2,+1,+0),
    not the already-1.75-2x-bumped one -- that's deliberate: the mate-
    mining regression's filestormopenfile/filestormpawn coefficients
    were fit against CSV data extracted using this original shape, so
    scaling *this* shape by the regression-derived conversion factor is
    the correct one-step translation (scaling the already-bumped shape
    again would double-apply the 2026-09-14 tuning). Magnitude derived
    the same way as KING_QUEEN_PROXIMITY_DANGER's self-play-validated
    -14/count: k = (validated queenproximity weight) / (queenproximity's
    own cleaned raw regression coefficient) =~ -14 per raw coefficient
    unit, applied to filestormpawn's raw coefficient (+0.374) and
    filestormopenfile's (+0.360) against the original table's own
    integer steps. Unvalidated by self-play as of this writing --
    expect this exact magnitude to move once tested, same as every
    other freshly-converted term here.

Parameters:

    POSITION *pos
    PAWN_HASH_ENTRY *pHash
    ULONG uColor

Return value:

    SCORE

**/
{
    static SCORE KingStormingPawnDefects[8] =
    {
        +0, -21, -16, -5, 0, 0, 0, 0
    };
    // 2026-10-04: NEW -- own-side shield-pawn bonus, the mirror image
    // of KingStormingPawnDefects above (same DISTANCE-indexed shape,
    // opposite color of pawn, opposite sign). Addresses a real gap:
    // nothing in _EvalKing previously rewarded keeping a shield pawn
    // (f2/g2/h2-shaped) on its home square, or penalized pushing it
    // away -- KingFileDefects only checks whether *a* pawn of either
    // color still exists somewhere on the file at all, which stays
    // satisfied even after an unforced push (g2-g3 doesn't change
    // uCountPerFile), and the front-flight-penalty below is a generic
    // "empty+unattacked gap" term with no notion that this square
    // specifically used to be a shield pawn's. Observed in practice:
    // the engine pushes its own king-shield pawns with no offsetting
    // cost from this function, then gets punished by the opponent
    // for the resulting weakened cover. Starting magnitude (+6 at
    // distance 1, i.e. still right in front of the king) is a guess,
    // not yet self-play validated -- same disclaimer as every other
    // freshly-added term in this function's history; expect it to
    // move once tested.
    static SCORE KingShieldPawnBonus[8] =
    {
        +0, +6, +3, +1, 0, 0, 0, 0
    };
    // Indexed by (fOwn << 1) | fEnemy: 0=open (neither side has a pawn
    // here), 1=half-open toward the enemy only (their pawn gone, ours
    // still there), 2=half-open toward us only (ours gone, theirs still
    // there), 3=closed (both present). Previously collapsed 1 and 2
    // into a single "half-open" bucket (uCountPerFile[WHITE][u]>0) +
    // (uCountPerFile[BLACK][u]>0) summed to 1 either way) -- split
    // 2026-10-08 since the two cases aren't symmetric (an enemy pawn
    // left behind is a real storming threat already priced by
    // KingStormingPawnDefects below, whereas our own pawn being the
    // only one left is comparatively mild).
    static SCORE KingFileDefects[4] =
    {
        -18, -10, -5, 0
    };
    // Old code's edge-file (a/h) kicker was a flat +1 counter-unit;
    // scaled by the same filestormopenfile-derived factor.
    static SCORE KING_FILE_EDGE_KICKER = -5;
    ULONG ufColor = FLIP(uColor);
    COOR c = KingPosition(pos, uColor);
    SCORE iScore = 0;
    COOR cFileSq, cSquare;
    ULONG u, v;
    BITBOARD bb;
    int w;

    for (w = -1; w <= 1; w++)
    {
        cFileSq = c + w;
        if (!IS_ON_BOARD(cFileSq))
        {
            continue;
        }
        u = FILE(cFileSq) + 1;
        v = ((pHash->uCountPerFile[uColor][u]  > 0) << 1) |
            (pHash->uCountPerFile[ufColor][u] > 0);
        ASSERT(v <= 3);
        iScore += KingFileDefects[v];
        iScore += ((v != 3) && ((u == 1) || (u == 8))) * KING_FILE_EDGE_KICKER;
        bb = pos->bbPawns[ufColor] & BBFILE[u - 1];
        if (bb)
        {
            if (uColor == WHITE)
            {
                cSquare = CoorFromBitBoardRank1ToRank8(&bb);
            }
            else
            {
                cSquare = CoorFromBitBoardRank8ToRank1(&bb);
            }
            ASSERT(IS_ON_BOARD(cSquare));
            iScore += KingStormingPawnDefects[DISTANCE(cSquare, c)];
        }

        // Shield-pawn bonus -- same file, but OUR OWN pawn, nearest
        // one to the king if doubled (same directional scan as the
        // enemy-storming-pawn lookup above, just over bbPawns[uColor]
        // instead of bbPawns[ufColor]).
        bb = pos->bbPawns[uColor] & BBFILE[u - 1];
        if (bb)
        {
            if (uColor == WHITE)
            {
                cSquare = CoorFromBitBoardRank1ToRank8(&bb);
            }
            else
            {
                cSquare = CoorFromBitBoardRank8ToRank1(&bb);
            }
            ASSERT(IS_ON_BOARD(cSquare));
            iScore += KingShieldPawnBonus[DISTANCE(cSquare, c)];
        }
    }
    return iScore;
}


static SCORE
_GetFileStormDefects(IN SEARCHER_THREAD_CONTEXT *ctx,
                     IN POSITION *pos,
                     IN const PAWN_HASH_ENTRY *pHash,
                     IN ULONG uColor)
/**

Routine description:

    EXPERIMENTAL, prototype-only (2026-09-05, board_representation/
    EVAL.md section 9's king-safety-hash discussion). Cache front end
    for _ComputeFileStormDefects, keyed on (pos->u64PawnSig, both
    kings' squares) -- deliberately covers only the DO_KING_SAFETY_
    THRESHOLD-gated "safety branch" term (measured ~96% hit rate in
    general/middlegame positions), not the u<8-gated "endgame branch"
    terms (king-supporting-own-passer, in/out-of-action), which
    measured a much worse ~75-85% hit rate in bare K+P endgames and
    are cheap enough there that caching them isn't expected to pay
    off -- those stay inline in _EvalKing, uncached.

    On a miss, computes *both* sides' defect counts and stores them
    together, so whichever king _EvalKing evaluates second within the
    same Eval() call (kings are always evaluated black-then-white) is
    a guaranteed hit -- only one real miss per position, not one per
    king.

    2026-09-15: return type/cache field changed ULONG -> SCORE along
    with _ComputeFileStormDefects -- see that function's comment. This
    function's own cache/probe/hit-rate mechanics are unaffected, only
    the value being cached changed shape. NOTE: CALIBRATE_POSITIONAL's
    two call sites (_RecordPositionalCalibration and the DumpPositional
    Calibration-ish block near EstimatePositionalScore) still treat this
    return value as a small unsigned index component
    (MINU(10, CountKingSafetyDefects(...) + _GetFileStormDefects(...)))
    -- now wrong now that this returns signed centipawns, but left
    alone by direct instruction (that non-default build flag's own
    recalibration is deferred as separate follow-up work, not part of
    this rewrite).

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx
    POSITION *pos
    PAWN_HASH_ENTRY *pHash
    ULONG uColor

Return value:

    SCORE

**/
{
    UINT64 u64Key = pos->u64PawnSig ^
        g_u64SigSeeds[KingPosition(pos, WHITE)][KING][WHITE] ^
        g_u64SigSeeds[KingPosition(pos, BLACK)][KING][BLACK];
    ULONG uSlot = (ULONG)u64Key & (KING_SAFETY_HASH_TABLE_SIZE - 1);
    KING_SAFETY_HASH_ENTRY *pEntry = &ctx->rgKingSafetyHash[uSlot];
#ifdef EVAL_TIME
    // 2026-10-03: moved from bare PERF_COUNTERS to EVAL_TIME, where the
    // other 32 cycle-counting sites in this file already live. These
    // three were the only rdtsc calls leaking into the standard build
    // profile -- two per king-safety hash probe, in one of the hottest
    // paths in the engine, and rdtsc is ~20-30 cycles and partially
    // serializing, so it defeats out-of-order execution exactly where
    // that hurts most. EVAL_TIME exists for precisely this measurement
    // ("make a version that counts cycles spent in eval", GNUmakefile),
    // so nothing is lost -- the capability just stops being paid for in
    // every match and every suite run.
    UINT64 u64Start = SystemReadTimeStampCounter();
#endif

    INC(ctx->sCounters.kingsafetyhash.u64Probes);
    if (pEntry->u64Key == u64Key)
    {
        INC(ctx->sCounters.kingsafetyhash.u64Hits);
#ifdef EVAL_TIME
        ctx->sCounters.kingsafetyhash.u64CyclesHit +=
            (SystemReadTimeStampCounter() - u64Start);
#endif
        return pEntry->iFileStormDefects[uColor];
    }
    pEntry->u64Key = u64Key;
    pEntry->iFileStormDefects[WHITE] = _ComputeFileStormDefects(pos, pHash, WHITE);
    pEntry->iFileStormDefects[BLACK] = _ComputeFileStormDefects(pos, pHash, BLACK);
#ifdef EVAL_TIME
    ctx->sCounters.kingsafetyhash.u64CyclesMiss +=
        (SystemReadTimeStampCounter() - u64Start);
#endif
    return pEntry->iFileStormDefects[uColor];
}


static SCORE
_GetKingActivityBonus(IN SEARCHER_THREAD_CONTEXT *ctx,
                      IN POSITION *pos,
                      IN const PAWN_HASH_ENTRY *pHash,
                      IN ULONG uColor,
                      IN COOR cKing)
/**

Routine description:

    Cache front end for _EvalKing's activity half (2026-10-06 safety/
    activity split): combines "supporting own passer" and "is this
    king out of the action" into one cached lookup, since both only
    ever apply together (same caller, same branch) and both depend on
    exactly the same inputs -- pawn structure plus uColor's own king
    square, nothing else. One key computation and one hash probe
    serve both instead of two. Only called when the ENEMY (xColor) is
    down to at most one non-king piece -- see _EvalKing.

    Per-king, not per-position: unlike _GetFileStormDefects (keyed on
    both kings' squares, since "is the king's position safe" depends
    on both), out-of-action's old formula subtracted the enemy king's
    own distance to make a symmetric "who's closer" value, but that
    only made sense paired with the old combined-both-sides gate
    (uTotalNonPawnsBothSides==2, true or false identically for both
    kings' calls). The new gate is per-call (keyed on xColor, each
    king's own enemy), so the two calls can legitimately disagree --
    one king's own position might qualify while the other's doesn't --
    and a shared symmetric value can no longer be "added once, during
    white's call" the way the old code assumed. Each call now computes
    and caches its own independent value instead.

    Narrower key (just this king's square, not both) than
    _GetFileStormDefects's as a direct consequence -- only this king's
    own moves can invalidate it, not the opponent's too, so this
    should measure a *better* hit rate than file-storm's own ~75-85%
    in this same low-material regime, not a worse one.

    PROVISIONAL, like the formulas it combines: neither weight has
    been through any self-play validation -- see the old out-of-action
    formula's own removed comment (git history) for the outlier bug
    that originally motivated shrinking its weight. Needs the same
    calibration discipline as every other king-safety magnitude in
    this file. Also trades away per-passer-square EVAL_TERM attribution
    (summed into one combined value instead) -- EVAL_DUMP tracing
    only, not used in release builds, by direct request for fewer
    instructions in this inner loop.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx
    POSITION *pos
    PAWN_HASH_ENTRY *pHash
    ULONG uColor : whose king this bonus is for
    COOR cKing : uColor's own king square (caller already has it --
        KingPosition(pos, uColor) redundantly)

Return value:

    SCORE

**/
{
    UINT64 u64Key = pos->u64PawnSig ^ g_u64SigSeeds[cKing][KING][uColor];
    ULONG uSlot = (ULONG)u64Key & (KING_SAFETY_HASH_TABLE_SIZE - 1);
    KING_SAFETY_HASH_ENTRY *pEntry = &ctx->rgKingSafetyHash[uSlot];
    SCORE i, iTotal;
    COOR cSquare;
    BITBOARD bb;

    INC(ctx->sCounters.kingactionhash.u64Probes);
    if (pEntry->u64ActionKey == u64Key)
    {
        INC(ctx->sCounters.kingactionhash.u64Hits);
        return pEntry->iActionBonus;
    }

    // Supporting own passer -- bb here is exactly the own-passer
    // squares at king-move distance 1 (g_KingAttacksBB is that mask
    // by construction), so every popped square counts; no separate
    // DISTANCE() filter or ASSERTs needed. The extra "leading the
    // pawn toward promotion" bonus applies iff the passer square is
    // in the king's own back ring (g_KingRingBackBB) -- side- and
    // front-ring passers still get the base rank-scaled support
    // bonus, just not this extra.
    iTotal = 0;
    bb = pHash->bbPasserLocations[uColor] & g_KingAttacksBB[cKing];
    while (IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&bb)))
    {
        i = 2;
        i += KING_SUPPORTING_OWN_PASSER_BY_RANK[uColor][RANK(cSquare)];
        i += 8 * ((COOR_TO_BB(cSquare) & g_KingRingBackBB[uColor][cKing]) != 0);
        iTotal += i;
    }

    // Out of action in KP-ish endgames, e.g.
    // 8/8/1p6/p6k/P3K3/8/1P6/8 w - - 0 11 -- how close this king is
    // to the whole pawn mass. The *2 preserves the old formula's own
    // scale (it used to be a differential, this is now a plain sum,
    // but the per-pawn magnitude is unchanged).
    i = 0;
    bb = pos->bbPawns[WHITE] | pos->bbPawns[BLACK];
    while (IS_ON_BOARD(cSquare = CoorFromBitBoardRank8ToRank1(&bb)))
    {
        i -= (SCORE)DISTANCE(cSquare, cKing);
    }
    iTotal += i * 2;

    pEntry->u64ActionKey = u64Key;
    pEntry->iActionBonus = iTotal;
    return iTotal;
}


#ifdef CALIBRATE_POSITIONAL
//
// board_representation/EVAL.md section 9 recalibration (2026-09-05):
// histogram of (cheap defect index -> real king-safety magnitude), one
// row per possible EstimatePositionalScore bucket, so a p90-per-row
// read after a calibration run over a large sample (curated suites or
// a slice of ecm.ep_, at real search depth so the distribution matches
// what the search tree actually sees, not just root positions) gives a
// fresh iKingSwingP90 table -- coarse cp bins, not raw samples, to keep
// this cheap enough to leave compiled into a whole search run rather
// than needing to buffer millions of individual values.
//
// 2026-09-15: bucket index fixed to MINU(10, CountKingSafetyDefects)
// ONLY, dropping _GetFileStormDefects -- it had drifted out of sync
// with EstimatePositionalScore's own real lookup index back on
// 2026-09-06 (_GetFileStormDefects was pulled out of that hot path for
// being too expensive to call on ~90% of Eval() calls regardless of
// exit, but this histogram's bucketing was never updated to match,
// silently refitting against an index EstimatePositionalScore was no
// longer using). Also: this histogram used to bin the pre-scale
// KING_SAFETY_BY_COUNTER magnitude, which was always <= 0 by
// construction; the 2026-09-15 linear-SCORE rewrite's iSafety can be
// mildly positive (a well-covered king with real back-rank escape
// squares and no attacks), so this now bins ABS(iSafety) -- by direct
// instruction, the rare positive case is small enough not to need its
// own separate treatment.
//
#define CALIBRATE_NUM_BUCKETS 11
#define CALIBRATE_BIN_WIDTH   5
#define CALIBRATE_NUM_BINS    200  // covers |raw king-safety magnitude| 0..999
static UINT64 g_CalibrateHist[CALIBRATE_NUM_BUCKETS][CALIBRATE_NUM_BINS];
UINT64 g_uCalibrateGateChecked = 0;
UINT64 g_uCalibrateGateTrue = 0;
UINT64 g_uCalibrateEvalCalls = 0;

static void
_RecordPositionalCalibration(IN SEARCHER_THREAD_CONTEXT *ctx,
                             IN POSITION *pos,
                             IN const PAWN_HASH_ENTRY *pHash,
                             IN ULONG uColor,
                             IN ULONG uRawMagnitude)
/**

Routine description:

    Bucket one real _EvalKing sample (this side's raw, pre-material-scaled
    king-safety magnitude) by the same cheap defect index
    EstimatePositionalScore would have used to estimate it, so a later
    DumpPositionalCalibration can compute a fresh p90-per-bucket table.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx
    POSITION *pos
    PAWN_HASH_ENTRY *pHash : unused as of 2026-09-15 (see the bucket-
        index fix in this file's #ifdef CALIBRATE_POSITIONAL comment
        above) -- kept in the signature for call-site stability.
    ULONG uColor
    ULONG uRawMagnitude : ABS(iSafety), before the
        REDUCED_MATERIAL_DOWN_SCALER scaling _EvalKing applies next --
        EstimatePositionalScore's table is looked up then scaled the same
        way, so the table itself should be fit against the unscaled value.

Return value:

    void

**/
{
    ULONG uIndex;
    ULONG uBin;

    // Only sample nodes Eval()'s own base-margin ("super lazy") gate
    // would actually pass through to EstimatePositionalScore in a real
    // build -- see ctx->fCalibrateCandidate's comment in chess.h.
    if (FALSE == ctx->fCalibrateCandidate)
    {
        return;
    }

    uIndex = MINU(10, CountKingSafetyDefects(pos, uColor));
    uBin = MINU(CALIBRATE_NUM_BINS - 1,
                uRawMagnitude / CALIBRATE_BIN_WIDTH);

    g_CalibrateHist[uIndex][uBin]++;
}


void
DumpPositionalCalibration(void)
/**

Routine description:

    Print a fresh iKingSwingP90[] table (p90 of the real, unscaled
    KING_SAFETY_BY_COUNTER value observed at each cheap defect-index
    bucket) from the histogram _RecordPositionalCalibration has been
    filling for the duration of this run. Only meaningful in a
    CALIBRATE_POSITIONAL build, after running a representative workload
    (the curated suites, or an ecm.ep_ slice, at real search depth --
    root-only positions won't exercise the distribution of positions the
    search tree actually evaluates).

Parameters:

    void

Return value:

    void

**/
{
    ULONG uIndex;
    ULONG uBin;
    UINT64 u64Total;
    UINT64 u64Running;
    SCORE iP90;

    Trace("Positional calibration: Eval() called %" COMPILER_LONGLONG_UNSIGNED_FORMAT " times\n",
          g_uCalibrateEvalCalls);
    Trace("Positional calibration: gate checked %" COMPILER_LONGLONG_UNSIGNED_FORMAT
          " times, true %" COMPILER_LONGLONG_UNSIGNED_FORMAT " times\n",
          g_uCalibrateGateChecked, g_uCalibrateGateTrue);
    Trace("Positional calibration (p90 per bucket, sample counts):\n");
    for (uIndex = 0; uIndex < CALIBRATE_NUM_BUCKETS; uIndex++)
    {
        u64Total = 0;
        for (uBin = 0; uBin < CALIBRATE_NUM_BINS; uBin++)
        {
            u64Total += g_CalibrateHist[uIndex][uBin];
        }
        if (0 == u64Total)
        {
            Trace("  bucket %2u: no samples\n", uIndex);
            continue;
        }
        u64Running = 0;
        iP90 = (SCORE)((CALIBRATE_NUM_BINS - 1) * CALIBRATE_BIN_WIDTH);
        for (uBin = 0; uBin < CALIBRATE_NUM_BINS; uBin++)
        {
            u64Running += g_CalibrateHist[uIndex][uBin];
            if (u64Running * 10 >= u64Total * 9)
            {
                iP90 = (SCORE)(uBin * CALIBRATE_BIN_WIDTH);
                break;
            }
        }
        Trace("  bucket %2u: p90=%d  (n=%" COMPILER_LONGLONG_UNSIGNED_FORMAT ")\n",
              uIndex, iP90, u64Total);
    }
}
#endif // CALIBRATE_POSITIONAL


// 2026-09-17: BASE_MARGIN_MAT_BUCKETS/WIDTH and _MaterialBucket() pulled
// out of the CALIBRATE_BASE_MARGIN/CALIBRATE_MARGIN_SAFETY-only guard
// below -- now also used unconditionally (see g_u64EvalExitByBucket in
// Eval(), and root.c's per-bucket exit-rate report) so a normal build
// can report exit rate by material bucket, not just the flat aggregate
// "Eval exit breakdown" line -- needed to see whether the p98/p2 margin
// redesign actually moved the exit rate in any given bucket, since the
// aggregate rate can mask buckets moving in opposite directions.
#define BASE_MARGIN_MAT_BUCKETS 8
#define BASE_MARGIN_MAT_WIDTH   8

static ULONG
_MaterialBucket(IN POSITION *pos)
/**

Routine description:

    Coarse combined-material bucket, 0 (bare kings) to
    BASE_MARGIN_MAT_BUCKETS-1 (full army). Originally CALIBRATE_BASE_
    MARGIN-only; now also used by the always-on per-bucket eval-exit-
    rate counters.

Parameters:

    POSITION *pos

Return value:

    ULONG : 0..BASE_MARGIN_MAT_BUCKETS-1

**/
{
    ULONG uCombined = pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK];
    return MINU(BASE_MARGIN_MAT_BUCKETS - 1, uCombined / BASE_MARGIN_MAT_WIDTH);
}

// Always-on per-material-bucket eval-exit counters -- separate from
// (and simpler than) the CALIBRATE_MARGIN_SAFETY machinery below: just
// "how many nodes exited via this tier, in this material bucket",
// enough to compute exit RATE per bucket (this array divided by the
// per-bucket sum across all three) without needing a special
// calibration build. See the five INC-site call pairs in Eval() below
// and root.c's report.
static UINT64 g_u64SuperLazyEvalsByBucket[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_u64LazyEvalsByBucket[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_u64FullEvalsByBucket[BASE_MARGIN_MAT_BUCKETS];

void
DumpEvalExitRateByBucket(void)
/**

Routine description:

    Print per-material-bucket eval exit rate (super lazy / lazy / full,
    as a percentage of that bucket's own total) -- command.c's
    "calibrate exitrate". Complements the flat aggregate "Eval exit
    breakdown" line (root.c, printed at the end of every search) by
    showing whether that aggregate is hiding buckets moving in opposite
    directions.

Parameters:

    void

Return value:

    void

**/
{
    ULONG m;

    Trace("Eval exit rate by material bucket (combined army scaler):\n");
    for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++)
    {
        UINT64 u64SL = g_u64SuperLazyEvalsByBucket[m];
        UINT64 u64L = g_u64LazyEvalsByBucket[m];
        UINT64 u64F = g_u64FullEvalsByBucket[m];
        UINT64 u64Total = u64SL + u64L + u64F;
        if (0 == u64Total)
        {
            Trace("  bucket %u (scaler %u-%u): no samples\n",
                  m, m * BASE_MARGIN_MAT_WIDTH,
                  (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1);
            continue;
        }
        Trace("  bucket %u (scaler %2u-%2u): n=%12" COMPILER_LONGLONG_UNSIGNED_FORMAT
              "  super=%5.2f%%  lazy=%5.2f%%  full=%5.2f%%\n",
              m, m * BASE_MARGIN_MAT_WIDTH,
              (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1,
              u64Total,
              100.0 * (double)u64SL / (double)u64Total,
              100.0 * (double)u64L / (double)u64Total,
              100.0 * (double)u64F / (double)u64Total);
    }
}


#ifdef CALIBRATE_BASE_MARGIN
//
// board_representation/EVAL.md section 9: is LAZY_EVAL_BASE_MARGIN (the
// flat, un-widened margin Eval() screens with before ever calling
// EstimatePositionalScore) well-sized? Tracks: once the gate passes and
// EstimatePositionalScore has widened the margin, does a real exit
// actually happen, broken out by the worse (max) of the two sides'
// cheap defect-index buckets? This answers "does the 'very dangerous'
// bucket (10) ever actually exit, or does its wide margin effectively
// rule it out". Doesn't require the lazy-exit machinery to be disabled
// (unlike the CALIBRATE_POSITIONAL king-safety work above) -- real
// exits still happen normally here, so this runs at normal speed.
//
// 2026-09-17: this used to also track a false-negative rate (the gate
// coming back false, then checking whether a real exit would've been
// available anyway) -- that required a flat-gate-false branch, which
// stopped existing once the flat pre-check itself was retired (see the
// `if (TRUE)` removal in Eval() below); removed alongside it rather
// than leaving permanently-zero counters.
//
// 2026-09-06: added a material dimension -- pos->uArmyScaler[WHITE] +
// pos->uArmyScaler[BLACK] (0-62), bucketed into 8 coarse bands, since
// the lazy/full cost ratio measured directly (opening/middlegame vs a
// bare K+P endgame) varies ~7x by material, and LAZY_EVAL_BASE_MARGIN
// is currently one flat constant across all of it.
static UINT64 g_uBaseMarginExitAttempted[BASE_MARGIN_MAT_BUCKETS][11];
static UINT64 g_uBaseMarginExitTaken[BASE_MARGIN_MAT_BUCKETS][11];

static ULONG
_MaxKingDangerBucket(IN SEARCHER_THREAD_CONTEXT *ctx,
                     IN POSITION *pos,
                     IN PAWN_HASH_ENTRY *pHash)
/**

Routine description:

    Cheap helper for CALIBRATE_BASE_MARGIN instrumentation only: the
    worse of the two sides' combined cheap defect-index buckets, same
    definition EstimatePositionalScore's iKingSwingP90 lookup uses.
    Re-reads CountKingSafetyDefects/_GetFileStormDefects rather than
    threading extra output params through EstimatePositionalScore --
    both hit the king-safety hash on a repeat call within the same
    Eval(), so this is cheap (see rgKingSafetyHash's "guaranteed
    intra-call hit" comment).

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx
    POSITION *pos
    PAWN_HASH_ENTRY *pHash

Return value:

    ULONG : 0-10

**/
{
    ULONG uWhite = MINU(10, CountKingSafetyDefects(pos, WHITE) +
                        _GetFileStormDefects(ctx, pos, pHash, WHITE));
    ULONG uBlack = MINU(10, CountKingSafetyDefects(pos, BLACK) +
                        _GetFileStormDefects(ctx, pos, pHash, BLACK));
    return MAXU(uWhite, uBlack);
}


void
DumpBaseMarginCalibration(void)
/**

Routine description:

    Print LAZY_EVAL_BASE_MARGIN calibration stats gathered so far this
    run: per-(material bucket, king-danger bucket) exit-attempted/
    exit-taken counts (command.c's "calibrate basemargin").

Parameters:

    void

Return value:

    void

**/
{
    ULONG m, u;

    for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++)
    {
        Trace("Base margin calibration -- material bucket %u "
              "(combined army scaler %u-%u):\n",
              m, m * BASE_MARGIN_MAT_WIDTH,
              (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1);
        for (u = 0; u <= 10; u++)
        {
            if (0 == g_uBaseMarginExitAttempted[m][u])
            {
                continue;
            }
            Trace("  king-danger bucket %2u: %" COMPILER_LONGLONG_UNSIGNED_FORMAT
                  " attempted, %" COMPILER_LONGLONG_UNSIGNED_FORMAT
                  " exited (%.2f%%)\n",
                  u, g_uBaseMarginExitAttempted[m][u],
                  g_uBaseMarginExitTaken[m][u],
                  (100.0 * (double)g_uBaseMarginExitTaken[m][u] /
                   (double)g_uBaseMarginExitAttempted[m][u]));
        }
    }
}
#endif // CALIBRATE_BASE_MARGIN


#ifdef CALIBRATE_MARGIN_SAFETY
//
// board_representation/EVAL.md section 9: for every node that actually
// took a lazy exit, how far off was the real (full-eval) score from
// the lazy-path score that got returned? The *maximum* observed swing,
// not just its p90, is what answers "how large would LAZY_EVAL_BASE_
// MARGIN have had to be before some exit here would have been
// unsound" -- unlike iKingSwingP90 (an estimate that's allowed to be
// wrong ~10% of the time by design), a used margin being exceeded even
// once is a genuine soundness question, so max is the right statistic
// here, not a percentile. Bucketed by combined material (same bucketing
// as CALIBRATE_BASE_MARGIN) since the earlier lazy/full cost-ratio
// measurement showed the two regimes are very different.
//
static UINT64 g_uMarginSwingMax[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uMarginSwingCount[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uMarginSwingSum[BASE_MARGIN_MAT_BUCKETS];
// 2026-09-17: max/avg alone hide the shape of the swing distribution --
// a bucket could have a huge max from one outlier and a small avg from
// a long thin tail of near-zero swings, or a genuinely fat middle.
// Histogram (same fixed-width-bin technique as RESID_HIST_* above,
// swings are always >= 0 so no negative-offset needed) plus a sum-of-
// squares accumulator lets DumpMarginSafetyCalibration report p10/p50/
// p90 and stdev per bucket, not just max/avg.
#define SWING_HIST_BIN_WIDTH 10
#define SWING_HIST_BINS 300  // covers [0, 3000) cp; observed max so far ~1300
static UINT64 g_uMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS];
static UINT64 g_uMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS];
// Genuine soundness check: did the swing ever exceed the *actual*
// (already-widened) margin that was used to justify this specific
// exit? Unlike the raw max above (which just says "how far things
// moved"), this directly answers "was any real exit actually unsound".
static UINT64 g_uMarginExceeded[BASE_MARGIN_MAT_BUCKETS];
// 2026-09-17: how many exceeded-margin FENs have already been printed
// for this (tier, material bucket) -- capped at MARGIN_EXCEEDED_FEN_
// SAMPLE_CAP so a run with hundreds of thousands of exceeded events
// (a real possibility while tuning loose margins) doesn't flood the
// log; just enough examples per bucket to eyeball by hand.
#define MARGIN_EXCEEDED_FEN_SAMPLE_CAP 5
static UINT64 g_uMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS];

// Same four counters, kept in a fully separate set for the super-lazy
// exit (eval.c's material-only check before the regular lazy gate).
// Its own SUPER_LAZY_MARGIN was never run through this harness when
// it was added -- a much cheaper, much-larger-required-gap check than
// the regular lazy exit, so mixing its swings into the buckets above
// would wash out both regimes' signal.
static UINT64 g_uSuperLazyMarginSwingMax[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uSuperLazyMarginSwingCount[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uSuperLazyMarginSwingSum[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uSuperLazyMarginSwingHist[BASE_MARGIN_MAT_BUCKETS][SWING_HIST_BINS];
static UINT64 g_uSuperLazyMarginSwingSumSq[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uSuperLazyMarginExceeded[BASE_MARGIN_MAT_BUCKETS];
static UINT64 g_uSuperLazyMarginExceededFenSamples[BASE_MARGIN_MAT_BUCKETS];

static void
_RecordMarginSafetySwingInto(IN OUT UINT64 *puMax,
                             IN OUT UINT64 *puCount,
                             IN OUT UINT64 *puSum,
                             IN OUT UINT64 *puSumSq,
                             IN OUT UINT64 puHist[][SWING_HIST_BINS],
                             IN OUT UINT64 *puExceeded,
                             IN OUT UINT64 *puFenSamples,
                             IN CHAR *szTierLabel,
                             IN POSITION *pos,
                             IN SCORE iSwing,
                             IN SCORE iActualMarginUsed)
{
    ULONG uMatBucket = _MaterialBucket(pos);
    ULONG uHistBin = MINU(SWING_HIST_BINS - 1,
                          (ULONG)iSwing / SWING_HIST_BIN_WIDTH);

    if (iSwing > iActualMarginUsed)
    {
        puExceeded[uMatBucket]++;
        // 2026-09-17: capped FEN sampler, a few examples per (tier,
        // bucket) to eyeball by hand -- generalized from a 2026-09-16
        // one-off (super-lazy bucket 0 alone) that first found a real
        // eval bug this way ("in/out of action"). Cheap: PositionToFen
        // only runs MARGIN_EXCEEDED_FEN_SAMPLE_CAP times per bucket for
        // the life of the process, not once per exceeded event.
        if (puFenSamples[uMatBucket] < MARGIN_EXCEEDED_FEN_SAMPLE_CAP)
        {
            CHAR *pszOutlierFen = PositionToFen(pos);
            if (NULL != pszOutlierFen)
            {
                puFenSamples[uMatBucket]++;
                Trace("MARGINSAFETY_EXCEEDED tier=%s bucket=%u swing=%d margin=%d fen=%s\n",
                      szTierLabel, uMatBucket, (int)iSwing,
                      (int)iActualMarginUsed, pszOutlierFen);
                SystemFreeMemory(pszOutlierFen);
            }
        }
    }

    ASSERT(iSwing >= 0);
    puCount[uMatBucket]++;
    puSum[uMatBucket] += (UINT64)iSwing;
    puSumSq[uMatBucket] += (UINT64)iSwing * (UINT64)iSwing;
    puHist[uMatBucket][uHistBin]++;
    if ((UINT64)iSwing > puMax[uMatBucket])
    {
        puMax[uMatBucket] = (UINT64)iSwing;
    }
}


static void
RecordMarginSafetySwing(IN POSITION *pos,
                        IN SCORE iSwing,
                        IN SCORE iActualMarginUsed)
/**

Routine description:

    Record one (material bucket, |real - lazy| swing) sample for
    DumpBaseMarginCalibration's margin-safety report, and check whether
    this specific exit's swing exceeded the actual margin that was used
    to justify it (a genuine unsoundness event, not just "large").

Parameters:

    POSITION *pos
    SCORE iSwing : >= 0
    SCORE iActualMarginUsed : the real (post-EstimatePositionalScore)
        alpha or beta margin this exit was taken under

Return value:

    void

**/
{
    _RecordMarginSafetySwingInto(g_uMarginSwingMax, g_uMarginSwingCount,
                                 g_uMarginSwingSum, g_uMarginSwingSumSq,
                                 g_uMarginSwingHist, g_uMarginExceeded,
                                 g_uMarginExceededFenSamples, "lazy",
                                 pos, iSwing, iActualMarginUsed);
}


static void
RecordSuperLazyMarginSafetySwing(IN POSITION *pos,
                                 IN SCORE iSwing,
                                 IN SCORE iActualMarginUsed)
/**

Routine description:

    Same as RecordMarginSafetySwing, but for the super-lazy exit's own
    separate bucket set -- see the comment on the g_uSuperLazyMargin*
    arrays above for why these are kept apart.

Parameters:

    POSITION *pos
    SCORE iSwing : >= 0
    SCORE iActualMarginUsed : SUPER_LAZY_MARGIN

Return value:

    void

**/
{
    _RecordMarginSafetySwingInto(g_uSuperLazyMarginSwingMax,
                                 g_uSuperLazyMarginSwingCount,
                                 g_uSuperLazyMarginSwingSum,
                                 g_uSuperLazyMarginSwingSumSq,
                                 g_uSuperLazyMarginSwingHist,
                                 g_uSuperLazyMarginExceeded,
                                 g_uSuperLazyMarginExceededFenSamples,
                                 "superlazy",
                                 pos, iSwing, iActualMarginUsed);
}


// Plain Newton's-method sqrt, no <math.h> -- chess.h's own VALUE_KING
// #defines INFINITY_SCORE as a board-eval sentinel, which collides with
// <math.h>'s own INFINITY_SCORE macro, so libm's sqrt() isn't available
// here without one shadowing the other. Variance is always small
// (swings are bounded well under 2^31), so a fixed handful of Newton
// iterations from a decent seed converges to full double precision.
static double
_Sqrt(IN double d)
{
    double dGuess;
    int i;

    if (d <= 0.0)
    {
        return 0.0;
    }
    dGuess = d;
    for (i = 0; i < 40; i++)
    {
        dGuess = 0.5 * (dGuess + (d / dGuess));
    }
    return dGuess;
}


// 2026-09-17: same idea as _PersistRawHistogramsToFile above, for the
// swing histograms -- lets multiple sharded runs (e.g. N chunks of a
// large position pool run in parallel on separate cores) be combined
// after the fact into one true aggregate: sum count/exceeded/sum/
// sumSq/histogram bins bucket-by-bucket across shard files, then
// recompute mean/stdev/percentiles from the combined totals. Doing
// this from raw counts is required for correctness -- percentiles
// (p10/p50/p90) can't be validly averaged across shards, only derived
// fresh from the combined histogram.
static void
_PersistMarginSwingHistogramToFile(IN FILE *f, IN CHAR *szTierLabel,
                                   IN UINT64 *puCount, IN UINT64 *puExceeded,
                                   IN UINT64 *puSum, IN UINT64 *puSumSq,
                                   IN UINT64 *puMax,
                                   IN UINT64 puHist[][SWING_HIST_BINS])
{
    ULONG b, i;

    for (b = 0; b < BASE_MARGIN_MAT_BUCKETS; b++)
    {
        fprintf(f, "%s %u %" COMPILER_LONGLONG_UNSIGNED_FORMAT " %"
                COMPILER_LONGLONG_UNSIGNED_FORMAT " %"
                COMPILER_LONGLONG_UNSIGNED_FORMAT " %"
                COMPILER_LONGLONG_UNSIGNED_FORMAT " %"
                COMPILER_LONGLONG_UNSIGNED_FORMAT,
                szTierLabel, b, puCount[b], puExceeded[b], puSum[b],
                puSumSq[b], puMax[b]);
        for (i = 0; i < SWING_HIST_BINS; i++)
        {
            fprintf(f, " %llu", (unsigned long long)puHist[b][i]);
        }
        fprintf(f, "\n");
    }
}


void
PersistMarginSafetyHistogramsToFile(IN CHAR *szPathOverride)
/**

Routine description:

    Write both tiers' swing histograms (plus count/exceeded/sum/sumSq/
    max per bucket) to a scratch file, in a format a small external
    script can sum bucket-by-bucket across multiple shard runs and
    recompute exact combined statistics from. See the comment on
    _PersistMarginSwingHistogramToFile above.

Parameters:

    CHAR *szPathOverride : output path, or NULL to use the default
        (/var/tmp/typhoon/marginsafety_raw_histograms.txt) -- pass a
        distinct path per shard when running N copies of a large
        position pool in parallel, since they'd otherwise all clobber
        the same default file.

Return value:

    void

**/
{
    FILE *f;
    CHAR *szPath = (NULL != szPathOverride) ? szPathOverride :
        "/var/tmp/typhoon/marginsafety_raw_histograms.txt";

    f = fopen(szPath, "w");
    if (NULL == f)
    {
        Trace("PersistMarginSafetyHistogramsToFile: could not open output file %s.\n",
              szPath);
        return;
    }
    fprintf(f, "# SWING_HIST_BINS=%d SWING_HIST_BIN_WIDTH=%d SWING_HIST_MIN=0\n",
            SWING_HIST_BINS, SWING_HIST_BIN_WIDTH);
    fprintf(f, "# format: <tier> <bucket> <count> <exceeded> <sum> <sumSq> "
               "<max> <bin0> <bin1> ... <binN-1>\n");
    _PersistMarginSwingHistogramToFile(f, "lazy", g_uMarginSwingCount,
                                       g_uMarginExceeded, g_uMarginSwingSum,
                                       g_uMarginSwingSumSq, g_uMarginSwingMax,
                                       g_uMarginSwingHist);
    _PersistMarginSwingHistogramToFile(f, "superlazy",
                                       g_uSuperLazyMarginSwingCount,
                                       g_uSuperLazyMarginExceeded,
                                       g_uSuperLazyMarginSwingSum,
                                       g_uSuperLazyMarginSwingSumSq,
                                       g_uSuperLazyMarginSwingMax,
                                       g_uSuperLazyMarginSwingHist);
    fclose(f);
    Trace("Raw margin-safety histograms written to %s\n", szPath);
}


static void
_DumpMarginSafetyCalibrationInto(IN CHAR *szLabel,
                                 IN UINT64 *puMax,
                                 IN UINT64 *puCount,
                                 IN UINT64 *puSum,
                                 IN UINT64 *puSumSq,
                                 IN UINT64 *puExceeded)
{
    ULONG m;

    Trace("%s -- |real - lazy| swing among exits taken, "
          "by material bucket:\n", szLabel);
    for (m = 0; m < BASE_MARGIN_MAT_BUCKETS; m++)
    {
        double dMean;
        double dVariance;
        double dStdev;

        if (0 == puCount[m])
        {
            Trace("  material bucket %u (scaler %u-%u): no exits taken\n",
                  m, m * BASE_MARGIN_MAT_WIDTH,
                  (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1);
            continue;
        }
        dMean = (double)puSum[m] / (double)puCount[m];
        // E[X^2] - E[X]^2; clamp to 0 to guard against fp rounding
        // producing a tiny negative just under zero.
        dVariance = ((double)puSumSq[m] / (double)puCount[m]) -
                    (dMean * dMean);
        if (dVariance < 0.0)
        {
            dVariance = 0.0;
        }
        dStdev = _Sqrt(dVariance);
        // 2026-09-17: no longer printing p10/p50/p90 here -- percentiles
        // don't combine validly across sharded runs (see
        // PersistMarginSafetyHistogramsToFile), so a single shard's
        // in-process percentile read stopped being the useful number
        // once the workflow moved to persisting raw histogram bins and
        // computing exact combined percentiles externally instead.
        Trace("  material bucket %u (scaler %u-%u): max=%"
              COMPILER_LONGLONG_UNSIGNED_FORMAT "  avg=%.1f  stdev=%.1f  "
              "(n=%"
              COMPILER_LONGLONG_UNSIGNED_FORMAT ")  exceeded=%"
              COMPILER_LONGLONG_UNSIGNED_FORMAT "\n",
              m, m * BASE_MARGIN_MAT_WIDTH,
              (m * BASE_MARGIN_MAT_WIDTH) + BASE_MARGIN_MAT_WIDTH - 1,
              puMax[m], dMean, dStdev,
              puCount[m], puExceeded[m]);
    }
}


void
DumpMarginSafetyCalibration(IN CHAR *szHistogramPathOverride)
/**

Routine description:

    Print, per material bucket, the max/avg/stdev |real - lazy| swing
    observed among nodes that actually took a lazy exit this run
    (command.c's "calibrate marginsafety") -- once for the regular lazy
    exit (LAZY_EVAL_BASE_MARGIN / EstimatePositionalScore) and once for
    the super-lazy exit (SUPER_LAZY_MARGIN), which is a different-enough
    regime (cheaper check, much larger required gap) that lumping the
    two together would hide whichever one is actually unsound. Either
    section's max is the number that answers "how large would that
    margin need to be, at that material level, before an exit there
    could have been unsound." Also persists the raw swing histograms
    to file (see PersistMarginSafetyHistogramsToFile) so percentiles
    can be computed exactly, including across multiple sharded runs.

Parameters:

    CHAR *szHistogramPathOverride : forwarded to
        PersistMarginSafetyHistogramsToFile -- NULL for the default path.

Return value:

    void

**/
{
    _DumpMarginSafetyCalibrationInto("Regular lazy margin safety",
                                     g_uMarginSwingMax, g_uMarginSwingCount,
                                     g_uMarginSwingSum, g_uMarginSwingSumSq,
                                     g_uMarginExceeded);
    _DumpMarginSafetyCalibrationInto("Super lazy margin safety",
                                     g_uSuperLazyMarginSwingMax,
                                     g_uSuperLazyMarginSwingCount,
                                     g_uSuperLazyMarginSwingSum,
                                     g_uSuperLazyMarginSwingSumSq,
                                     g_uSuperLazyMarginExceeded);
    PersistMarginSafetyHistogramsToFile(szHistogramPathOverride);
}
#endif // CALIBRATE_MARGIN_SAFETY


// 2026-09-16/17: shared, file-scope tables for the margin_a/margin_b
// (super-lazy, in Eval() below) and margin_a'/margin_b'
// (EstimatePositionalScore, regular lazy, right after this) margin
// constructions. King safety is ARMY-ONLY for both tiers (no
// CountKingSafetyDefects call from either -- a joint attacker-army x
// defect-count table was considered for regular lazy specifically, but
// dropped: CountKingSafetyDefects is slow despite being bitboard-based,
// not worth paying for if the simpler table is already good enough;
// it stays in the codebase for its existing, unrelated search
// extension/reduction-gate use). Residual is NOT shared between tiers,
// despite living together here -- iResidualP2/98ByOwnArmy is scoped
// to regular lazy's own baseline (after bishop pairs: excludes pawns/
// passers/bad-trade/bishop-pairs, since regular lazy already has all
// of that by the time it asks); iSuperLazyResidualP2/98ByOwnArmy is
// scoped to super-lazy's own baseline (pure material: INCLUDES pawns/
// passers/bad-trade/bishop-pairs, since super-lazy has none of it yet).
// Using the regular-lazy-scoped table for super-lazy was a real bug in
// the first version of this redesign -- it silently excluded exactly
// the terms super-lazy needed most and got quietly papered over with a
// MAX() against the old flat floor, which defeated the whole point of
// building a position-specific estimate. Fixed by measuring the right
// thing instead of re-adding a workaround.
//
// Speed/accuracy knob: measured exceeded rate (fraction of lazy/
// super-lazy exits where the real full-eval score actually would have
// landed back across alpha/beta -- i.e. this lazy exit was WRONG) by
// percentile choice, both from the same 30k-position stratified pool,
// same `sd 6` conditions, via CALIBRATE_MARGIN_SAFETY's `calibrate
// marginsafety`. Bucket numbering here is the MATERIAL bucket
// (_MaterialBucket: combined non-pawn army scaler for BOTH sides,
// divided by 8 -- 0-7) -- NOT the same bucketing as the per-side
// army-scaler/4 buckets the percentile tables below are keyed by.
// Buckets 0-1 never take a regular-lazy exit at all (see
// LAZY_EVAL_MIN_MATERIAL) so have no regular-lazy row.
//
//   material bucket:            2       3       4       5       6       7
//   (combined scaler)        (16-23) (24-31) (32-39) (40-47) (48-55) (56-63)
//   -----------------------  ------- ------- ------- ------- ------- -------
//   regular lazy, p90/p10:    0.97%   0.48%   0.72%   1.61%   1.54%   0.72%
//   regular lazy, p98/p2:    0.046%  0.013%  0.010%  0.029%  0.032%  0.041%
//
//   material bucket:            1       2       3       4       5       6       7
//   (combined scaler)        (8-15)  (16-23) (24-31) (32-39) (40-47) (48-55) (56-63)
//   -----------------------  ------- ------- ------- ------- ------- ------- -------
//   super lazy, p90/p10:      9.43%   5.08%   3.73%   1.32%   1.14%   1.99%   0.54%
//   super lazy, p98/p2:       1.08%  0.349%  0.209%  0.045%  0.063%  0.069%  0.018%
//
// (Super-lazy has no material-bucket-0 row: excluded entirely, see the
// bucket-0 comment at its exclusion gate below.)
//
// 2026-09-17 re-recalibration: switched from p90/p10 to p98/p2 given
// the above -- p90/p10 exceeded on a non-trivial fraction of exits
// (regular lazy: 0.5-1.6% across buckets; super-lazy: 0.5-9.4%, worst
// in the low-material buckets), p98/p2 brings every bucket in both
// tiers under 1.1%, an order of magnitude tighter. If p98/p2 still
// isn't tight enough once self-play validates it, p99/p1 is the next
// lever -- re-derive via `calibrate residual` against the same 30k
// pool, no new position sample needed.
// All four tables below are FINAL, derived from the same 30k-position
// stratified pool (~104M-240M samples/bucket for residual/king,
// buckets keyed by scaler/4). Full percentile spread recorded so a
// future re-tightening (e.g. p99/p1) can read values straight off
// these charts without re-running the 30k pool -- only the two
// _P2By.../_P98By... lines actually feed the margin construction
// below; min/p1/p5/p10/p50/p90/p95/p99/max are kept for reference.
//
// Residual by OWN army-scaler bucket (regular-lazy baseline: excludes
// pawns/passers/bad-trade/bishop-pairs):
//   bucket 0 (scaler 0-3):   n=104187433 min=-144 p1=-30  p2=-10  p5=-10  p10=-10  p50=10  p90=110 p95=130 p98=190 p99=230 max=767
//   bucket 1 (scaler 4-7):   n=125821895 min=-166 p1=-10  p2=-10  p5=-10  p10=10   p50=50  p90=150 p95=210 p98=250 p99=290 max=817
//   bucket 2 (scaler 8-11):  n=239860406 min=-174 p1=-30  p2=-30  p5=-10  p10=-10  p50=30  p90=130 p95=170 p98=230 p99=270 max=761
//   bucket 3 (scaler 12-15): n=190456720 min=-209 p1=-50  p2=-30  p5=-30  p10=-10  p50=30  p90=110 p95=130 p98=190 p99=230 max=708
//   bucket 4 (scaler 16-19): n=216350902 min=-220 p1=-70  p2=-70  p5=-50  p10=-30  p50=30  p90=90  p95=110 p98=150 p99=170 max=735
//   bucket 5 (scaler 20-23): n=189558383 min=-225 p1=-70  p2=-50  p5=-30  p10=-30  p50=30  p90=70  p95=90  p98=130 p99=150 max=728
//   bucket 6 (scaler 24-27): n=135722645 min=-231 p1=-90  p2=-70  p5=-50  p10=-30  p50=10  p90=70  p95=90  p98=110 p99=130 max=760
//   bucket 7 (scaler 28-31): n=164358044 min=-256 p1=-110 p2=-110 p5=-90  p10=-90  p50=-30 p90=30  p95=50  p98=70  p99=90  max=796
// 2026-09-17 BEST-GUESS #2: guess #1 (p95/p5 uniformly) measured
// 0.002-0.270% on a 500-position sample (buckets 2-7) -- still under
// the ~0.4% target, especially buckets 4-5 (0.002% each). Per direct
// instruction, loosened buckets 2-5 one more step to p90/p10 (values
// read off the chart above, no new run); buckets 6-7 already looked
// close to target at p95/p5 (0.270%/0.152%) and are left unchanged.
// Buckets 0-1 never take a regular-lazy exit at all (LAZY_EVAL_MIN_
// MATERIAL) so their values are moot either way. Caveat: the 500-
// position sample is noisy (small event counts in low buckets, and
// not truly 500 independent draws -- a single game's tree can dominate
// a material bucket's node population), so this is still a guess
// pending the next full 30k-position `calibrate marginsafety` run.
// 2026-09-17 BEST-GUESS #3: real 30k-pool re-check of guess #2 (not
// the noisy 500-position sample) measured bucket2=0.385% (right on
// target) but buckets 3-7 all 0.048-0.099%, still well under the
// 0.4-0.5% target -- loosened further to p85/p15 (exact values from
// the persisted raw histogram, /var/tmp/typhoon/residual_raw_
// histograms.txt -- see hist_percentile.py). Bucket 2 left unchanged
// (already at target).
// 2026-09-17 BEST-GUESS #4: buckets 0-2 left at guess #3 (0.06-0.39%
// measured, buckets 0-1 take no lazy exits so moot). Buckets 3-7
// measured 0.048-0.099%, well under the ~0.4-0.5% target -- loosened
// one more notch (values read off the persisted 30k histogram via
// hist_percentile.py, no new sample needed): bucket 3 p85/p15 ->
// p80/p20, bucket 4 p85/p15 -> p80(tie)/p20, bucket 5 p85/p15 ->
// p85(tie)/p20, bucket 6 p85/p15 -> p75/p25, bucket 7 p90/p20-ish ->
// p75/p25 (P98 only, P2 already at its floor). Re-verify with a full
// `calibrate marginsafety` pass -- not expected to land exactly on
// target given cross-bucket confounds (see guess #3 comment above).
// 2026-09-17 BEST-GUESS #5: buckets 3-5 loosened one more notch
// (p80/p20-ish -> p70/p30, values from the persisted 30k histogram).
// Bucket 0-2, 6-7 unchanged pending their own re-check (guess #4's
// 30k run showed bucket 2 already over target without being touched,
// and buckets 6-7 already over target from guess #4's loosening --
// see command history).
// 2026-09-17 BEST-GUESS #6: targeting ~0.66% in every bucket. Bucket 2
// was drifting up untouched (0.72% guess #4 -> 1.04% guess #5) --
// tightened p90/p10-ish -> p80/p20. Bucket 5 was under target (0.39%)
// -- loosened a tad, p70/p30 -> p90/p30 (P98 side only).
// 2026-09-17 BEST-GUESS #7: targeting ~0.66% in every bucket.
// Bucket 2 (1.62%, way over) -- guess #6's "tighten" actually
// narrowed the margin by mistake (tighten = lower exceeded rate =
// WIDEN the percentile spread, not narrow it); corrected direction,
// widened past guess #5's own (-10,130) to (-30,190) i.e. p97/p3.
// Buckets 3/4/6 (0.71-0.74%, slightly over) widened a little (P98
// +20 each). Bucket 5 (0.30%, under) narrowed back (P98 70->50,
// reverting guess #6's accidental widen). Bucket 7 (0.47%, under)
// narrowed a little (P2 -70->-50).
// 2026-09-17 BEST-GUESS #8: buckets 3-5 came in well under target
// (0.27-0.39% vs ~0.66%) -- narrowed further for speed (guess #5's
// bucket 5 narrow was too small a step, barely moved anything;
// bigger step this time). Bucket 3: p75/p30 -> p60/p40. Bucket 4:
// P98 only, p75/p40 -> p55/p40 (P2 unchanged, bin ties at that end).
// Bucket 5: p65/p35-ish -> p55/p45, moved both sides this time.
// Buckets 0-2/6-7 untouched pending their own re-check.
// 2026-09-18: restored to the guess-#11 values (11 rounds of
// calibration against the 30k-position pool and the 200k-position
// cross-sectional run, see the guess #1-11 history above) after
// briefly suspecting -- and ruling out, via the 16:15 ZFS snapshot
// still showing a winning match_play series with guesses #9/#10
// already applied -- that this table's loosening was the source of
// the 2026-09-17 self-play regression. The real cause was util.c's
// WalkPV/MakeUserMove change (reverted separately).
static const SCORE iResidualPessimisticByOwnArmy[8] =
{
    -10, -10, -10, 10, -10, 30, -10, -50,
};
static const SCORE iResidualOptimisticByOwnArmy[8] =
{
    130, 210, 170, 50, 70, 30, 50, -10,
};
// Super-lazy-scoped residual by OWN army-scaler bucket (material-only
// baseline: includes pawns/passers/bad-trade/bishop-pairs):
//   bucket 0 (scaler 0-3):   n=104187433 min=-363 p1=-110 p2=-90 p5=-50 p10=-30 p50=30 p90=210 p95=290 p98=410 p99=530 max=2383
//   bucket 1 (scaler 4-7):   n=125821895 min=-356 p1=-70  p2=-50 p5=-30 p10=-10 p50=90 p90=290 p95=370 p98=490 p99=830 max=2456
//   bucket 2 (scaler 8-11):  n=239860406 min=-341 p1=-70  p2=-50 p5=-30 p10=-10 p50=70 p90=250 p95=330 p98=430 p99=530 max=2065
//   bucket 3 (scaler 12-15): n=190456720 min=-324 p1=-70  p2=-50 p5=-30 p10=-10 p50=70 p90=230 p95=290 p98=390 p99=450 max=2183
//   bucket 4 (scaler 16-19): n=216350902 min=-343 p1=-90  p2=-70 p5=-50 p10=-30 p50=50 p90=190 p95=250 p98=310 p99=370 max=1946
//   bucket 5 (scaler 20-23): n=189558383 min=-299 p1=-70  p2=-50 p5=-30 p10=-10 p50=70 p90=170 p95=230 p98=290 p99=330 max=1959
//   bucket 6 (scaler 24-27): n=135722645 min=-322 p1=-90  p2=-70 p5=-50 p10=-30 p50=50 p90=150 p95=190 p98=250 p99=290 max=1921
//   bucket 7 (scaler 28-31): n=164358044 min=-304 p1=-90  p2=-90 p5=-70 p10=-50 p50=10 p90=90  p95=130 p98=170 p99=210 max=2039
// 2026-09-17 BEST-GUESS #3: real 30k-pool re-check of guess #2 revealed
// the 500-position sample had misled guess #2 in the dangerous
// direction on two buckets: material bucket 1 (reverted to p98/p2
// based on a 500-position reading of 0.035%) actually measured 1.13%
// at full scale, and material bucket 3 (table never touched at all)
// measured 0.94% -- a real cross-bucket confound (changing OTHER
// buckets' margins shifts real search behavior/tree shape everywhere,
// so even an untouched bucket's measured exceeded rate moves). Per-
// side buckets 0-3 tightened to p99/p1 (exact values from the
// persisted raw histogram) to address both -- material buckets 1 and 3
// are populated by a diffuse mix of per-side bucket combinations, not
// a clean 1:1 mapping, so this can't precisely target either bucket
// alone, only reduce risk broadly in the low-army region feeding both.
// Buckets 4-6 measured 0.22-0.30%, still under target -- loosened
// further to p85/p15. Bucket 7 (0.15%) and the king table (negligible
// spread above p90 in every bucket, confirmed against the persisted
// histogram) left unchanged. Real search-tree-shape changes are
// expected from this (not just a measurement artifact) -- re-verify
// with a full `calibrate marginsafety` pass, best-effort, not
// expected to land exactly on target for every bucket given the
// diffuse material-bucket-to-per-side-bucket mapping.
// 2026-09-17 BEST-GUESS #4: bucket 1 was the worst outlier at 1.13%
// measured (target ~0.4-0.5%) -- tightened one more notch past p99/p1,
// to p99.5/p0.5 (values from the persisted 30k histogram). Buckets 0
// and 2-3 left at guess #3 (bucket 3 measured 0.94%, also over target,
// but a diffuse material-bucket confound with bucket 1 -- see guess #3
// comment above -- so left alone pending its own re-check rather than
// guessing a second simultaneous change). Buckets 4-7 measured
// 0.15-0.30%, well under target -- loosened one more notch: buckets
// 4-6 p85/p15 -> p80/p20, bucket 7 p90/p10 -> p85/p15.
// 2026-09-17 BEST-GUESS #5: bucket 3 was over target (0.94% guess #3,
// 1.23% guess #4, moving the wrong direction despite never being
// touched -- a cross-bucket confound from bucket 1's changes) --
// tightened past p99/p1 to p99.5/p0.5, same lever used for bucket 1.
// Bucket 7 was still under target (0.15%/0.29%) -- loosened one more
// notch, p85/p15 -> p75/p25 (P98 side only; P2 already at p85's floor).
// 2026-09-17 BEST-GUESS #6: targeting ~0.66% in every bucket. Bucket
// 1 (0.458%, under target) was at p99.5/p0.5 -- backed off a tiny bit
// to p99/p1. Bucket 3 (1.11%, worst outlier, already at p99.5/p0.5)
// has no looser-percentile lever left in this histogram's resolution
// -- padded a fixed +120/-20 beyond p99.5/p0.5 instead. Bucket 6
// (0.96%, over target, was p80/p20) tightened to p90/p10. Bucket 7
// (0.36%, under target, was p75/p25) loosened a tad, P2 side only
// (p25 -> p30-ish).
// 2026-09-17 BEST-GUESS #7: targeting ~0.66% in every bucket.
// Bucket 1 (0.49%, slightly under) narrowed a little (P2 -70->-50).
// Buckets 2/4/6 (0.68/0.61/0.71%) already close enough -- left
// alone. Bucket 3 (1.09%, still worst, already past p99.5) widened
// further via a bigger pad (-110,650) -> (-150,850). Buckets 5/7
// (0.54%/0.56%, slightly under) narrowed a little (P98 -20 each).
// 2026-09-17 BEST-GUESS #9: same 200k/sd3 cross-sectional finding as
// the regular-lazy table above, new target 1.5%. Bucket 2 (2.99%,
// worst of all despite never being touched before -- already sitting
// at p99/p0.5, percentile table exhausted) padded further, same lever
// used for bucket 3 previously. Bucket 3 (1.95%, least-bad of these
// three but still over, already heavily padded) padded a bit more.
// Bucket 6 (2.19%) widened p90/p10 -> p96/p6.
// 2026-09-17 BEST-GUESS #10: target ~1-1.5%. Bucket 1 (0.34%, well
// under) loosened, p99/p2-ish -> ~p98/p4. Bucket 2 (3.45%, worst --
// got WORSE after widening in guess #9 despite already sitting past
// p99.5) padded further again regardless; this bucket has resisted
// two widening passes in a row, likely the same cross-bucket-combo
// issue diagnosed for bucket 3 earlier (material bucket != per-side
// bucket, diffuse mapping) rather than something this table alone can
// fix -- flagging for a real root-cause dig rather than more blind
// widening if this doesn't help either. Buckets 3-7 left alone.
// 2026-09-17 BEST-GUESS #11: bucket 2 (2.97%, still worst after three
// widening rounds in a row -- see guess #10's note, likely a
// cross-bucket-combo issue this table alone can't fully fix) padded
// further again. Rest left alone.
// 2026-09-18: restored to the guess-#11 values (see the matching note
// on iResidualPessimisticByOwnArmy above) after ruling out this
// table's loosening as the cause of the 2026-09-17 self-play
// regression -- the 16:15 ZFS snapshot already had guesses #9/#10
// applied and was still winning. The real cause was util.c's WalkPV/
// MakeUserMove change (reverted separately).
static const SCORE iSuperLazyResidualPessimisticByOwnArmy[8] =
{
    -110, -30, -190, -170, 10, 10, -50, -10,
};
static const SCORE iSuperLazyResidualOptimisticByOwnArmy[8] =
{
    530, 490, 1050, 950, 150, 110, 190, 40,
};
// King safety by ATTACKER army-scaler bucket:
//   bucket 0 (scaler 0-3):   n=104187433 min=-68  p1=-10  p2=10   p5=10   p10=10   p50=10  p90=30  p95=30  p98=50 p99=50 max=165
//   bucket 1 (scaler 4-7):   n=125821895 min=0    p1=10   p2=10   p5=10   p10=10   p50=10  p90=30  p95=30  p98=50 p99=50 max=162
//   bucket 2 (scaler 8-11):  n=239860406 min=-89  p1=-30  p2=-30  p5=-30  p10=-10  p50=10  p90=10  p95=10  p98=30 p99=30 max=162
//   bucket 3 (scaler 12-15): n=190456720 min=-176 p1=-70  p2=-70  p5=-50  p10=-50  p50=-10 p90=-10 p95=10  p98=10 p99=10 max=137
//   bucket 4 (scaler 16-19): n=216350902 min=-307 p1=-190 p2=-170 p5=-130 p10=-110 p50=-30 p90=-10 p95=-10 p98=-10 p99=10 max=129
//   bucket 5 (scaler 20-23): n=189558383 min=-354 p1=-250 p2=-230 p5=-190 p10=-130 p50=-50 p90=-30 p95=-10 p98=-10 p99=-10 max=45
//   bucket 6 (scaler 24-27): n=135722645 min=-401 p1=-270 p2=-250 p5=-170 p10=-150 p50=-70 p90=-30 p95=-10 p98=-10 p99=-10 max=13
//   bucket 7 (scaler 28-31): n=164358044 min=-394 p1=-190 p2=-170 p5=-130 p10=-90  p50=-50 p90=-10 p95=-10 p98=-10 p99=10  max=6
static const SCORE iKingP2ByAttackerArmy[8] =
{
    10, 10, -30, -70, -170, -230, -250, -170,
};
static const SCORE iKingP98ByAttackerArmy[8] =
{
    50, 50, 30, 10, -10, -10, -10, -10,
};

// 2026-09-17: p50 tables, same 30k-position pool, same bucketing as
// their P2/P98 siblings above -- but used for a different purpose:
// a signed, unbounded (well, table-bounded) *typical-value estimate*
// of that side's own missing positional terms, fed to QSearch's
// futility margin as iPositional[side] on a lazy/super-lazy exit
// (matches full-eval's own iPositional convention exactly -- see
// Eval()'s "Adjust dynamic positional component" block below, which
// computes a side's *own* real positional score minus its material,
// not a relative-to-opponent quantity). This is deliberately NOT the
// p98/p2 pessimistic/optimistic pairing margin_a/margin_b use --
// p50 is the right statistic for a bias correction, p98/p2 is the
// right statistic for a soundness bound. iPositional[color] =
// iKingP50ByAttackerArmyOnly[opponent's army bucket] (opponent is the
// attacker of this side's own king) + iResidualP50ByOwnArmy[this
// side's own army bucket] (or the super-lazy-scoped sibling, for the
// super-lazy exit).
//   residual p50 (regular-lazy baseline), by OWN army bucket:
//     10, 50, 30, 30, 30, 30, 10, -30
//   super-lazy-scoped residual p50 (material-only baseline), by OWN army bucket:
//     30, 90, 70, 70, 50, 70, 50, 10
//   king safety p50, by ATTACKER army bucket:
//     10, 10, 10, -10, -30, -50, -70, -50
static const SCORE iResidualP50ByOwnArmy[8] =
{
    10, 50, 30, 30, 30, 30, 10, -30,
};
static const SCORE iSuperLazyResidualP50ByOwnArmy[8] =
{
    30, 90, 70, 70, 50, 70, 50, 10,
};
static const SCORE iKingP50ByAttackerArmy[8] =
{
    10, 10, 10, -10, -30, -50, -70, -50,
};


static void
EstimatePositionalScore(IN SEARCHER_THREAD_CONTEXT *ctx,
                        IN POSITION *pos,
                        IN PAWN_HASH_ENTRY *pHash,
                        IN OUT SCORE *piAlphaMargin,
                        IN OUT SCORE *piBetaMargin)
/**

Routine description:

    Before doing an early lazy eval, look at the position and widen
    the alpha/beta margins to account for the positional terms that
    have not been computed yet at this point in Eval() -- king safety
    plus a flat residual covering mobility, passers, and everything
    else that genuinely requires full evaluation to find out.

    Both terms below are calibrated from measured data (CALIBRATE_
    POSITIONAL instrumentation, 200M full-eval samples: for each
    value, p90 of the *actual* score swing between this point in
    Eval() and full-eval completion, so the resulting margin is wrong
    (too narrow) on at most ~10% of calls, in either bucket. See
    conversation history for the percentile tables -- if re-tuning,
    regenerate them, don't hand- edit these numbers.

    Note: king safety and "everything else" turned out to be close to
    independent of piece count and of each other, so summing their
    two p90s (rather than deriving one joint p90) is a deliberately
    conservative (wider than strictly necessary) combination.

    O(1) -- no attack bitboard generation -- so it's safe to call
    whenever the cheap material-only lazy check (the caller's
    first-pass margin) wasn't enough to resolve the cutoff on its own.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx : unused as of 2026-09-06
        (_GetFileStormDefects, the only user, was pulled out of this
        hot path -- see the iKingSwingP90 staleness comment below);
        kept in the signature for call-site stability.
    POSITION *pos
    PAWN_HASH_ENTRY *pHash : unused as of 2026-09-06, same reason as
        ctx above. pHash->iScore is already folded into pos->iScore by
        this point regardless, and the passer-specific estimate this
        used to compute turned out to be negligible next to the
        residual term below.
    SCORE *piAlphaMargin, *piBetaMargin : widened in place, identically
        (no measured basis for an asymmetric alpha/beta split)

Return value:

    void

**/
{
    // 2026-09-16 redesign: replaces the old symmetric "sum both sides'
    // unscaled p90 magnitude, rescale by attacker army at runtime"
    // construction entirely -- that mechanism pooled the p90 fit
    // across every material level for a given CountKingSafetyDefects
    // bucket, then linearly rescaled by attacker army at use time; that
    // rescale assumed a linear relationship between "how much raw
    // danger a defect-count implies" and "how much material the
    // attacker actually has" that the real terms (each individually
    // gated on specific attacking pieces existing) don't obey -- a
    // structural mismatch, not just a stale fit (see conversation
    // history for the full derivation).
    //
    // New approach: two direct, jointly-collected percentile tables --
    // king safety bucketed by the ATTACKER's own army scaler (danger
    // to a king is a function of the attacker's material, not the
    // king-owner's), and residual (mobility/trapped/misc, with
    // material/pawns/passers/bad-trade/bishop-pairs/king safety already
    // excluded) bucketed by each side's OWN army scaler (residual is
    // relative/congestion-driven, not attacker-driven, unlike king
    // safety -- bucketing it by one side's own army alone, ignoring the
    // enemy, was tried and came back noisy/non-monotonic; the
    // differential does not, but this per-side percentile construction
    // sidesteps needing the differential directly by keying each side's
    // OWN contribution off its OWN army only, then combining per-side
    // via the asymmetric construction below).
    //
    // The margin construction itself mirrors this file's existing
    // QSearch futility precedent (iPositional is returned per-color,
    // not as a single "estimate minus full eval" blob, because a
    // combined delta lets the two sides' real swings partially cancel
    // and hides the structure that actually matters) -- and is the
    // same operation as futility pruning, one stack frame up: for the
    // fail-high check (score - margin_a > beta), soundness requires
    // assuming the most PESSIMISTIC-for-me, OPTIMISTIC-for-my-opponent
    // outcome for each term; the fail-low check (score + margin_b <
    // alpha) requires the mirror. For every term, uniformly (no sign-
    // flipping needed regardless of whether the raw term is usually
    // positive or negative):
    //
    //     margin_a = [opponent's p90(term) - my p10(term)], summed over terms
    //     margin_b = [my p90(term) - opponent's p10(term)], summed over terms
    //
    // King safety is cross-referenced (my king's term uses the
    // OPPONENT's army bucket, since they're the attacker; the
    // opponent's king term uses MY army bucket) -- residual is not
    // (each side's residual is keyed by that side's own army).
    //
    // PROVISIONAL tables below: from a 200-position stratified
    // (material-balanced) sample, ~8.76M full-eval samples -- adequate
    // for validating the construction and getting real numbers in
    // place, but due for a refresh from the much larger 30k-position
    // stratified histogram run once it lands (board_representation/
    // EVAL.md section 9 / 2026-09-16 super-lazy speed investigation).
    // Re-derive via `calibrate residual` (DUMP_RESIDUAL_SAMPLES build).
    // Uses the file-scope army-only king table (iKingP2/98ByAttacker-
    // ArmyOnly) and residual table (iResidualP2/98ByOwnArmy), shared
    // with super-lazy's identical construction below in Eval(). A
    // joint (attacker-army x defect-count) king table was considered
    // (CountKingSafetyDefects would supersede the army-only estimate
    // once we're already committed to the more expensive lazy-eval
    // path) but deliberately dropped -- CountKingSafetyDefects is slow
    // despite being bitboard-based, not worth paying for here if the
    // simpler army-only table is already good enough. It stays in the
    // codebase for its existing, unrelated use as a search extension/
    // reduction gate (search.c/searchsup.c) -- just no longer called
    // from eval's margin construction at all, either tier.
    ULONG uColor = pos->uToMove;
    ULONG xColor = FLIP(uColor);
    ULONG uMyBucket = MINU(7, pos->uArmyScaler[uColor] / 4);
    ULONG uOppBucket = MINU(7, pos->uArmyScaler[xColor] / 4);
    SCORE iSelfPessimisticEnemyOptimisticMargin, iSelfOptimisticEnemyPessimisticMargin;

    iSelfPessimisticEnemyOptimisticMargin = MAX0((iKingP98ByAttackerArmy[uMyBucket] -
                     iKingP2ByAttackerArmy[uOppBucket]) +
                    (iResidualOptimisticByOwnArmy[uOppBucket] -
                     iResidualPessimisticByOwnArmy[uMyBucket]));
    iSelfOptimisticEnemyPessimisticMargin = MAX0((iKingP98ByAttackerArmy[uOppBucket] -
                     iKingP2ByAttackerArmy[uMyBucket]) +
                    (iResidualOptimisticByOwnArmy[uMyBucket] -
                     iResidualPessimisticByOwnArmy[uOppBucket]));

    // Caller's iBetaMargin gates "score - margin > beta" (fail-high,
    // needs margin_a); iAlphaMargin gates "score + margin < alpha"
    // (fail-low, needs margin_b).
    //
    // 2026-09-17: the flat iSwingFloorByArmy MAX() floor that used to
    // sit here is GONE, for the same reason super-lazy's analogous
    // floor was already dropped (see Eval()'s super-lazy margin
    // construction, above) -- a MAX() against a much larger flat number
    // just silently overrides the position-specific estimate in most
    // cases, defeating the entire point of building it. margin_a/
    // margin_b now stand alone. If CALIBRATE_MARGIN_SAFETY turns up a
    // real, non-trivial exceeded rate once this is validated against
    // the 30k pool, the fix is tightening the percentile choice (e.g.
    // p95/p5 or p99/p1), not resurrecting a flat backstop.
    *piAlphaMargin += iSelfOptimisticEnemyPessimisticMargin;
    *piBetaMargin += iSelfPessimisticEnemyOptimisticMargin;
}


//
// ======================================================================
//

static void
_RecordTrappedCandidate(IN OUT POSITION *pos,
                         IN ULONG uColor,
                         IN COOR c,
                         IN BITBOARD bbEscapes)
/**

Routine description:

    Record a trapped-piece candidate for uColor -- either a genuinely
    zero-mobility piece (bbEscapes passed as 0: nothing to re-derive,
    see _EvalBishop's comment), or a bishop/knight deferred because its
    own partial-information mobility count was low but nonzero
    (bbEscapes is that piece's own bbMobility snapshot at nomination
    time). Used by _EvalBishop/_EvalKnight/_EvalRook/_EvalQueen; the
    actual attacked-or-not check, and (for a deferred candidate) the
    final mobility re-derivation, happen later in _EvalTrappedPieces.
    Capped at ARRAY_LENGTH(pos->cTrapped[0]) candidates per side --
    extras are just dropped, not a real concern in practice.

Parameters:

    POSITION *pos,
    ULONG uColor,
    COOR c,
    BITBOARD bbEscapes

Return value:

    void

**/
{
    if (pos->uNumTrapped[uColor] < ARRAY_LENGTH(pos->cTrapped[uColor]))
    {
        pos->bbTrappedEscapes[uColor][pos->uNumTrapped[uColor]] = bbEscapes;
        pos->cTrapped[uColor][pos->uNumTrapped[uColor]++] = c;
    }
}


static void
_EvalBishop(IN OUT POSITION *pos,
            IN COOR c,
            IN PAWN_HASH_ENTRY *pHash,
            IN BITBOARD bbEnemyRQK)
/**

Routine description:

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,
    BITBOARD bbEnemyRQK -- enemy rook|queen|king, precomputed once per
        color by Eval()'s driver instead of rebuilt by every bishop of
        that color (see MOBILITY_BITBOARD_REWRITE.md) -- depends only on
        static piece locations, no eval-ordering dependency.

Return value:

    FLAG

**/
{
    static const BITBOARD bbColorSq[2] = { 0x55aa55aa55aa55aaULL,
                                           0xaa55aa55aa55aa55ULL };
    static const COOR cBishopAtHome[2][2] =
    {
        { C8, F8 }, // BLACK
        { C1, F1 }  // WHITE
    };
    ULONG uColor;
    ULONG xColor;
    BITBOARD bb;
    BITBOARD bbMask;
    BITBOARD bbPc;
    SCORE i;
    ULONG u;
    ULONG uTotalMobility;
    PIECE p;

    ASSERT(IS_ON_BOARD(c));
    p = pos->rgSquare[c].pPiece;
    ASSERT(p && IS_BISHOP(p));
    uColor = GET_COLOR(p);
    xColor = FLIP(uColor);

    // Undeveloped minor piece; maybe penalized later in EvalKing.
    pos->uMinorsAtHome[uColor] += (c == cBishopAtHome[uColor][0]);
    pos->uMinorsAtHome[uColor] += (c == cBishopAtHome[uColor][1]);
    ASSERT(pos->uMinorsAtHome[uColor] <= 4);

    // Good and bad bishops given pawn structure (own and enemy,
    // stationary and transient) on this bishop's color complex --
    // cached per (color, complex) in the pawn hash, since none of it
    // depends on which square of that complex the bishop actually
    // sits on. See the cache population in the pawn-hash-miss path
    // above (_EvalPawns's FOREACH_COLOR block) for the full semantics.
    bbMask = bbColorSq[IS_SQUARE_WHITE(c)];
    i = pHash->iBishopColorScore[uColor][IS_SQUARE_WHITE(c)];
    EVAL_TERM(uColor,
              BISHOP,
              c,
              pos->iScore[uColor],
              i,
              "good/bad bishop pawns");

    // Still needed below: "non-stationary pawns of either color on
    // this color complex," used by the mobility walk's
    // BMOB_FRIEND_PAWN case (see its comment just below).
    bbPc = ~(pHash->bbStationaryPawns[WHITE] |
             pHash->bbStationaryPawns[BLACK]) & bbMask;

    //
    // Bishop mobility (and update attack tables) -- single magic-bitboard
    // probe, no chain walk (see MOBILITY_BITBOARD_REWRITE.md). The old
    // seven-case BMobCaseTable collapses to pure mask arithmetic over the
    // one-shot first-blocker attack set:
    //   - terminal enemy non-pawn (minor/rook/queen/king): counts
    //     unconditionally -- this is a capture, always "real" mobility.
    //   - empty or terminal enemy pawn: counts unless pawn-unsafe -- both
    //     terminal-square categories together are exactly "not
    //     friend-occupied and not enemy-non-pawn-occupied," the same
    //     partition knight's reduction uses.
    //   - terminal friendly, non-stationary pawn on this bishop's own
    //     color complex: still counts -- bbPc (already computed above for
    //     the good/bad transient-pawn scoring) is exactly "non-stationary
    //     pawns of either color on this color complex."
    //   - any other friendly piece (knight/rook/king): blocks, no count.
    //
    // Deliberately NOT replicated: mobility/connectivity credit for
    // squares beyond a friendly bishop/queen or enemy rook/queen/king --
    // a bishop cannot physically move past a piece it would capture in
    // one ply, so that was never "real mobility" to begin with (dropping
    // it is a correctness fix, not just a simplification). See
    // MOBILITY_BITBOARD_REWRITE.md for the king-ring x-ray replacement,
    // which is the one piece of information this loses that's worth
    // deliberately replacing below.
    //
    BITBOARD bbAttack = _BishopAttacksBB(c, pos->bbOccupied);
    BITBOARD bbEnemySame = pos->bbPieces[xColor][BISHOP] |
        pos->bbPieces[xColor][KNIGHT];
    BITBOARD bbUnsafeForMinor = pos->bbPawnAttacks[xColor];
    BITBOARD bbEnemyPawnHere = bbAttack & pos->bbPawns[xColor];
    BITBOARD bbTransientHere = bbAttack & pos->bbPawns[uColor] & bbPc;
    BITBOARD bbEnemyGEHere = bbAttack & bbEnemyRQK;
    BITBOARD bbMobility;
    BITBOARD bbXray;

    pos->bbMinorAttacks[uColor] |= bbAttack;

    bbMobility = (bbAttack & ~pos->bbOccupied & ~bbUnsafeForMinor) |
        (bbAttack & bbEnemySame) |
        bbEnemyGEHere |
        (bbEnemyPawnHere & ~bbUnsafeForMinor) |
        bbTransientHere;

    //
    // King-ring x-ray, replacing the old chain's attack-bit population:
    // only pay for an extra magic probe when this bishop already
    // directly attacks an enemy rook/queen/king square (bbEnemyGEHere,
    // already computed above for mobility -- free to test). Every bit
    // in bbEnemyGEHere is, by construction, the terminal blocker of a
    // *different* diagonal ray, so masking all of them off at once and
    // re-probing in a single magic lookup gives the exact same union a
    // per-blocker loop would (removing one ray's blocker can't affect a
    // different ray's result) -- no need to isolate and remove them one
    // at a time. No deeper chaining needed either way, since the only
    // consumer (_EvalKingSafety) only ever ANDs this against the king's
    // ring, never walks further.
    //
    bbXray = bbEnemyGEHere ?
        _BishopAttacksBB(c, pos->bbOccupied & ~bbEnemyGEHere) : 0;
    pos->bbMinorXrayAttacks[uColor] |= bbXray;

    // Pseudo-mobility bonus for squares seen past the higher-value
    // blocker -- see BISHOP_XRAY_MOBILITY_BY_SQUARES's comment. bbXray
    // already includes the blocker's own square (redundant with
    // bbAttack, which already counts it as a capture), so subtracting
    // bbAttack leaves exactly the net-new squares revealed behind it.
    EVAL_TERM(uColor,
              BISHOP,
              c,
              pos->iScore[uColor],
              BISHOP_XRAY_MOBILITY_BY_SQUARES[
                  MINU(FastCountBits(bbXray & ~bbAttack), 8)],
              "xray pseudo-mobility");

    uTotalMobility = FastCountBits(bbMobility);

    ASSERT(uTotalMobility <= 13);

    //
    // uTotalMobility here is necessarily pessimistic-as-an-upper-bound
    // (not pessimistic-as-a-lower-bound): at this point in Eval() only
    // enemy PAWN attacks are known, so a square next to the enemy king,
    // or covered by an enemy piece that hasn't run its own eval pass
    // yet, still looks safe and gets counted. More attack information
    // can only mark MORE squares unsafe later, never fewer -- so this
    // count can only ever be too high, never too low.
    //
    // That asymmetry is exactly why a genuinely 0-mobility bishop is
    // scored and recorded immediately rather than deferred: 0 is
    // already the floor, so a fuller attack picture later can't change
    // it (0 minus more unsafe squares is still 0) -- there is nothing
    // to gain by waiting. A LOW but nonzero count, however, could
    // easily still be an overcount (the classic case that motivated
    // this: a pawn push that cuts off the bishop's retreat leaves two
    // "safe" squares right next to the enemy king that are only safe
    // because the king's own attacks aren't in the table yet) -- defer
    // those to _EvalTrappedPieces, which re-derives the true count once
    // both kings and every piece type have contributed to the attack
    // tables, instead of locking in a score that a fuller picture might
    // revise downward.
    //
    if (uTotalMobility < EVAL_MOBILITY_CAREFULLY_BELOW)
    {
        if (uTotalMobility == 0)
        {
            EVAL_TERM(uColor,
                      BISHOP,
                      c,
                      pos->iScore[uColor],
                      BISHOP_MOBILITY_BY_SQUARES[0],
                      "bishop mobility");
        }
        _RecordTrappedCandidate(pos, uColor, c, bbMobility);
    }
    else // reasonable mobility
    {
        EVAL_TERM(uColor,
                  BISHOP,
                  c,
                  pos->iScore[uColor],
                  BISHOP_MOBILITY_BY_SQUARES[uTotalMobility],
                  "bishop mobility");
    }

    //
    // Bonus for a bishop that's securely placed -- safe from ever
    // being challenged by an enemy pawn, and (checked below) defended
    // by a friendly one -- near the enemy king. This is a
    // bishop-specific king-tropism/outpost bonus.
    //
    bb = pos->bbPawns[xColor] &
        (~pHash->bbStationaryPawns[xColor]);
    if (TRUE == _IsSquareSafeFromEnemyPawn(pos, c, bb))
    {
        // Defended (and defending) a friendly pawn.
        if (pos->bbPawnAttacks[uColor] & COOR_TO_BB(c))
        {
#ifdef DEBUG
            p = BLACK_PAWN | uColor;
            ASSERT(((IS_ON_BOARD(c + 17 * g_iBehind[uColor]) &&
                     (pos->rgSquare[c + 17 * g_iBehind[uColor]].pPiece==p)) ||
                    ((IS_ON_BOARD(c + 15 * g_iBehind[uColor])) &&
                     (pos->rgSquare[c + 15 * g_iBehind[uColor]].pPiece==p))));
#endif
            u = DISTANCE(c, KingPosition(pos, xColor));
            i = BISHOP_UNASSAILABLE_BY_DIST_FROM_EKING[u];
            EVAL_TERM(uColor,
                      BISHOP,
                      c,
                      pos->iReducedMaterialDownScaler[uColor],
                      i,
                      "[scaled] unassailable");
        }
    }
}

static void
_EvalKnight(IN OUT POSITION *pos,
            IN COOR c,
            IN PAWN_HASH_ENTRY *pHash)
/**

Routine description:

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,

Return value:

    FLAG

**/
{
    static const int iPawnStart[2] = { -17, +15 };
    static const COOR cKnightAtHome[2][2] =
    {
        { B8, G8 }, // BLACK
        { B1, G1 }  // WHITE
    };
    PIECE p;
    COOR cSquare;
    BITBOARD bb;
    ULONG uColor;
    ULONG xColor;
    ULONG uPawnsSupporting;
    ULONG uMobilitySquares;
    BITBOARD bbMobility;
    SCORE i;
    ULONG uDist;

    p = pos->rgSquare[c].pPiece;
    ASSERT(p && IS_KNIGHT(p));
    uColor = GET_COLOR(p);
    ASSERT(IS_VALID_COLOR(uColor));
    xColor = FLIP(uColor);

    // Unmoved piece; potentially penalized in EvalKing.
    pos->uMinorsAtHome[uColor] += (c == cKnightAtHome[uColor][0]);
    pos->uMinorsAtHome[uColor] += (c == cKnightAtHome[uColor][1]);
    ASSERT(pos->uMinorsAtHome[uColor] <= 4);

    // Centrality bonus
    EVAL_TERM(uColor,
              KNIGHT,
              c,
              pos->iScore[uColor],
              KNIGHT_CENTRALITY_BONUS[c],
              "board centrality");

    // Give a bonus to knights on a closed / busy board.
    ASSERT(pHash->uClosedScaler <= 32);
    EVAL_TERM(uColor,
              KNIGHT,
              c,
              pos->iScore[uColor],
              KNIGHT_IN_CLOSED_POSITION[pHash->uClosedScaler],
              "in closed/open position");

    // Outposted knights.  See if square c is safe from enemy pawns;
    // if so give bonus for outposted knight which increases the
    // closer it is to the enemy king and the more pawns it has
    // supporting it.
    uDist = DISTANCE(c, KingPosition(pos, xColor));
    ASSERT((uDist > 0) && (uDist <= 8));
    bb = pos->bbPawns[xColor] &
        (~pHash->bbStationaryPawns[xColor]);
    if (TRUE == _IsSquareSafeFromEnemyPawn(pos, c, bb))
    {
        // Count the number of supporting pawns the knight has
        uPawnsSupporting = 0;
        p = BLACK_PAWN | uColor;
        cSquare = c + iPawnStart[uColor];
        uPawnsSupporting = (IS_ON_BOARD(cSquare) &&
                            (pos->rgSquare[cSquare].pPiece == p));
        cSquare += 2;
        uPawnsSupporting += (IS_ON_BOARD(cSquare) &&
                             (pos->rgSquare[cSquare].pPiece == p));
        ASSERT(uPawnsSupporting <= 2);

        // Give a bonus based on distance from enemy king
        i = KNIGHT_UNASSAILABLE_BY_DIST_FROM_EKING[uDist] +
            KNIGHT_WITH_N_PAWNS_SUPPORTING[uPawnsSupporting];
        EVAL_TERM(uColor,
                  KNIGHT,
                  c,
                  pos->iReducedMaterialDownScaler[uColor],
                  i,
                  "[scaled] unassailable/support");

        // Now, if there's zero or one supporter see if the enemy has a
        // bishop the color of the knight it could capture with.
        if (uPawnsSupporting != 2)
        {
            if (IS_SQUARE_WHITE(c))
            {
                if (WhiteSqBishopCount(pos, xColor))
                {
                    EVAL_TERM(uColor,
                              KNIGHT,
                              c,
                              pos->iScore[uColor],
                              -(i / 2),
                              "not safe from enemy B");
                }
            }
            else
            {
                if (FastCountBits(pos->bbPieces[xColor][BISHOP]) -
                    WhiteSqBishopCount(pos, xColor))
                {
                    EVAL_TERM(uColor,
                              KNIGHT,
                              c,
                              pos->iScore[uColor],
                              -(i / 2),
                              "not safe from enemy B");
                }
            }
        }
    }
    else // not outposted
    {
        // Still good to be close to the enemy king.
        i = KNIGHT_KING_TROPISM_BONUS[uDist];
        EVAL_TERM(uColor,
                  KNIGHT,
                  c,
                  pos->iReducedMaterialDownScaler[uColor],
                  i,
                  "[scaled] enemy king tropism");
    }

    // Give a bonus for blockading an enemy backward pawn.
    cSquare = c + 16 * g_iAhead[uColor];
    bb = pHash->bbStationaryPawns[xColor];
    if (bb & COOR_TO_BB(cSquare))
    {
        ASSERT(pos->rgSquare[cSquare].pPiece);
        ASSERT(IS_PAWN(pos->rgSquare[cSquare].pPiece));
        EVAL_TERM(uColor,
                  KNIGHT,
                  c,
                  pos->iScore[uColor],
                  KNIGHT_ON_INTERESTING_SQUARE_BY_RANK[uColor][RANK(c)],
                  "blockades enemy pawn");
    }

    //
    // Removed 2026-08-30 ("A knight with an open file behind it is
    // good"): dubious chess reasoning on its own (open-file bonuses
    // are classically a rook concept -- knights don't use files the
    // way rooks do) compounded by reusing KNIGHT_ON_INTERESTING_SQUARE
    // _BY_RANK, the *same* table as the backward-pawn-blockade bonus
    // just above, for a completely unrelated condition. That reuse
    // muddied what the table means and made it untunable
    // independently for either concept.
    //

    //
    // Do mobility and piece relevance. Also update attack tables.
    //
    // board_representation/EVAL.md section 1b/2: g_KnightAttacksBB[c]
    // (generate.c's precomputed table, already used by move
    // generation) is exactly the old per-square g_iNDeltas walk's
    // destination set, IS_ON_BOARD baked in at table-build time -- no
    // per-square branch, no mailbox read, no switch. Knights never
    // x-ray or have a battery partner, so the old NMobCaseTable's four
    // cases collapse to two bitboard masks: NMOB_ENEMY_OTHER (any
    // enemy non-pawn -- count unconditionally) and NMOB_MOBILE_SQUARE
    // (empty or enemy pawn -- count unless pawn-unsafe). NMOB_FRIEND
    // needs no term at all, it's just "neither of the above."
    //
    {
        BITBOARD bbAttack = g_KnightAttacksBB[c];
        BITBOARD bbFriendOcc = _BuildFriendlySideBB(pos, uColor);
        BITBOARD bbEnemyNonPawnOcc = _BuildFriendlySideBB(pos, xColor) &
                                      ~pos->bbPawns[xColor];
        BITBOARD bbUnsafeForMinor = pos->bbPawnAttacks[xColor];

        pos->bbMinorAttacks[uColor] |= bbAttack;

        bbMobility = (bbAttack & bbEnemyNonPawnOcc) |
                     (bbAttack & ~bbFriendOcc & ~bbEnemyNonPawnOcc &
                      ~bbUnsafeForMinor);
        uMobilitySquares = FastCountBits(bbMobility);
    }
    ASSERT(uMobilitySquares >= 0);
    ASSERT(uMobilitySquares <= 8);

    // See _EvalBishop's comment above its own identically-structured
    // mobility scoring for why 0-mobility is scored immediately while
    // a low-but-nonzero count is deferred to _EvalTrappedPieces instead.
    if (uMobilitySquares < EVAL_MOBILITY_CAREFULLY_BELOW)
    {
        if (uMobilitySquares == 0)
        {
            EVAL_TERM(uColor,
                      KNIGHT,
                      c,
                      pos->iScore[uColor],
                      KNIGHT_MOBILITY_BY_COUNT[0],
                      "knight mobility");
        }
        _RecordTrappedCandidate(pos, uColor, c, bbMobility);
    }
    else // reasonable mobility
    {
        EVAL_TERM(uColor,
                  KNIGHT,
                  c,
                  pos->iScore[uColor],
                  KNIGHT_MOBILITY_BY_COUNT[uMobilitySquares],
                  "knight mobility");
    }
}

static void
_EvalRook(IN OUT POSITION *pos,
          IN COOR c,
          IN PAWN_HASH_ENTRY *pHash,
          IN BITBOARD bbEnemyQK,
          IN BITBOARD bbUnsafeForRook)
/**

Routine description:

Parameters:

    IN POSITION *pos,
    IN COOR c,
    IN PAWN_HASH_ENTRY *pHash,
    IN BITBOARD bbEnemyQK -- enemy queen|king, precomputed once per color
        by Eval()'s driver (see MOBILITY_BITBOARD_REWRITE.md) -- depends
        only on static piece locations.
    IN BITBOARD bbUnsafeForRook -- enemy pawn|minor attacks, precomputed
        once per color right before the rook loops start, valid because
        both colors' knight+bishop passes are already complete by then.

Return value:

    FLAG

**/
{
    PIECE p;
    ULONG uColor;
    ULONG uTotalMobility;
    BITBOARD bbMobility;
    SCORE i;

    ASSERT(IS_ON_BOARD(c));
    p = pos->rgSquare[c].pPiece;
    ASSERT(p && IS_ROOK(p));
    uColor = GET_COLOR(p);
    ASSERT(IS_VALID_COLOR(uColor));

    ULONG xColor = FLIP(uColor);
    ASSERT(IS_VALID_COLOR(xColor));

    BITBOARD bbFile = BBFILE[FILE(c)];
    BITBOARD bbFriendPawns = pos->bbPawns[uColor] & bbFile;
    BITBOARD bbEnemyPawns = pos->bbPawns[xColor] & bbFile;
    SCORE bonus = ROOK_FULL_HALF_OPEN_BONUS[bbFriendPawns != 0][bbEnemyPawns != 0];

    bonus += (SCORE)((bbEnemyPawns & pHash->bbPasserLocations[xColor]) != 0) *
        ROOK_WITH_ENEMY_PASSER;
    bonus += (SCORE)((bbFriendPawns & pHash->bbPasserLocations[uColor]) != 0) *
        ROOK_WITH_FRIEND_PASSER;
    bonus += (SCORE)((COOR_TO_BB(c) & BBROOK_7TH_RANK[uColor]) != 0) *
        ROOK_ON_SEVENTH_BONUS;
    EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], bonus,
              "file/passer bonus");

    //
    // Rooks increase in value as pawns come off:
    //
    // "A further refinement would be to raise the knight's value by
    // 1/16 and lower the rook's value by 1/8 for each pawn above five
    // of the side being valued, with the opposite adjustment for each
    // pawn short of five."
    //                                             --Larry Kaufman, IM
    //                               "Evaluation of Material Imbalance"
    //
    EVAL_TERM(uColor,
              ROOK,
              c,
              pos->iScore[uColor],
              ROOK_VALUE_AS_PAWNS_COME_OFF[pHash->uTotalPawnCount],
              "increase in value/pawns");
    ASSERT(pHash->uTotalPawnCount ==
           (FastCountBits(pos->bbPawns[uColor]) + FastCountBits(pos->bbPawns[xColor])));

    //
    // Rook mobility (and update attack tables) -- single magic-bitboard
    // probe, no chain walk (see MOBILITY_BITBOARD_REWRITE.md). The old
    // RMobCaseTable's six cases collapse to mask arithmetic over the
    // one-shot first-blocker attack set:
    //   - terminal enemy rook/queen/king: counts unconditionally -- a
    //     capture is always "real" mobility regardless of value.
    //   - empty or terminal enemy pawn/knight/bishop: counts unless the
    //     square is attacked by an enemy pawn or minor -- both
    //     terminal-square categories together are exactly "not
    //     friend-occupied and not enemy-rook/queen/king-occupied," the
    //     same partition bishop/knight's reductions use.
    //   - any friendly piece: blocks, no count. A friendly rook
    //     specifically also earns the connected-rook bonus (direct
    //     attack only now, not chained through a further blocker).
    //
    // Deliberately NOT replicated: mobility/connectivity credit for
    // squares beyond a friendly rook/queen or enemy queen/king -- a
    // rook cannot physically move past a piece it would capture in one
    // ply, so that was never "real mobility" to begin with (dropping it
    // is a correctness fix, not just a simplification). See
    // MOBILITY_BITBOARD_REWRITE.md for the king-ring x-ray replacement,
    // which is the one piece of information this loses that's worth
    // deliberately replacing below.
    //
    BITBOARD bbAttack = _RookAttacksBB(c, pos->bbOccupied);
    BITBOARD bbEnemyOcc = _BuildFriendlySideBB(pos, xColor);
    BITBOARD bbEnemySame = pos->bbPieces[xColor][ROOK];
    BITBOARD bbEnemyGEHere = bbAttack & bbEnemyQK;
    BITBOARD bbEnemyLEHere = bbAttack & bbEnemyOcc &
        ~bbEnemySame & ~bbEnemyGEHere;
    BITBOARD bbFriendRookHere = bbAttack & pos->bbPieces[uColor][ROOK];
    BITBOARD bbXray;

    pos->bbRookAttacks[uColor] |= bbAttack;

    bbMobility = (bbAttack & ~pos->bbOccupied & ~bbUnsafeForRook) |
        (bbAttack & bbEnemySame) |
        bbEnemyGEHere |
        (bbEnemyLEHere & ~bbUnsafeForRook);

    // Connected-rook bonus -- direct attack only now; see the comment
    // above.
    while (bbFriendRookHere)
    {
        COOR cBlocker = CoorFromBitBoardRank8ToRank1(&bbFriendRookHere);
        FLAG fHoriz = (RANK(cBlocker) == RANK(c));
        EVAL_TERM(uColor,
                  ROOK,
                  cBlocker,
                  pos->iScore[uColor],
                  (ROOK_CONNECTED_HORIZ * fHoriz +
                   ROOK_CONNECTED_VERT * FLIP(fHoriz)),
                  "rooks connected");
    }

    //
    // King-ring x-ray, replacing the old chain's attack-bit population:
    // only pay for an extra magic probe when this rook already directly
    // attacks the enemy queen or king square (bbEnemyGEHere, already
    // computed above for mobility -- free to test). bbEnemyGEHere has
    // at most two bits (queen, king), each the terminal blocker of a
    // *different* ray -- masking both off at once and re-probing in a
    // single magic lookup gives the same union a per-blocker loop would
    // (one ray's blocker removal can't affect the other ray's result).
    // No deeper chaining needed either way, since the only consumer
    // (_EvalKingSafety) only ever ANDs this against the king's ring,
    // never walks further.
    //
    bbXray = bbEnemyGEHere ?
        _RookAttacksBB(c, pos->bbOccupied & ~bbEnemyGEHere) : 0;
    pos->bbRookXrayAttacks[uColor] |= bbXray;

    // Pseudo-mobility bonus for squares seen past the queen/king blocker
    // -- see ROOK_XRAY_MOBILITY_BY_SQUARES's comment, same reasoning as
    // bishop's identical term.
    EVAL_TERM(uColor,
              ROOK,
              c,
              pos->iScore[uColor],
              ROOK_XRAY_MOBILITY_BY_SQUARES[
                  MINU(FastCountBits(bbXray & ~bbAttack), 8)],
              "xray pseudo-mobility");

    uTotalMobility = FastCountBits(bbMobility);
    ASSERT(uTotalMobility <= 14);
    ASSERT(pos->uArmyScaler[xColor] <= 31);

    // Same partial-information reasoning, and same immediate-0/deferred-
    // low-nonzero split, as _EvalBishop's identically-structured
    // mobility scoring (see its comment) -- bbUnsafeForRook above only
    // knows about enemy pawn/minor attacks, not the enemy king's or (for
    // a rook specifically) a not-yet-evaluated enemy queen's, so a low
    // nonzero count here is still liable to be an overcount.
    if (uTotalMobility < EVAL_MOBILITY_CAREFULLY_BELOW)
    {
        _RecordTrappedCandidate(pos, uColor, c, bbMobility);
    }
    i = ROOK_MOBILITY_BY_SQUARES[uTotalMobility];
    i *= (int)(REDUCED_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]] + 1);
    i /= 8;
    EVAL_TERM(uColor,
              ROOK,
              c,
              pos->iScore[uColor],
              i,
              "rook mobility");
}


static void
_EvalQueen(IN OUT POSITION *pos,
           IN COOR c,
           IN PAWN_HASH_ENTRY *pHash,
           IN BITBOARD bbEnemyQK,
           IN BITBOARD bbUnsafeForQueen)
/**

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,
    BITBOARD bbEnemyQK -- enemy queen|king, precomputed once per color by
        Eval()'s driver -- identical formula to _EvalRook's bbEnemyQK, so
        the same precomputed value is reused for both (see
        MOBILITY_BITBOARD_REWRITE.md).
    BITBOARD bbUnsafeForQueen -- precomputed once per color right before
        the queen loops start, valid because both colors' pawn/minor/rook
        passes are already complete by then.

Return value:

    FLAG

**/
{
    PIECE p = pos->rgSquare[c].pPiece;
    ULONG uColor;
    ULONG xColor;
    ULONG uTotalMobility;

    ASSERT(IS_ON_BOARD(c));
    ASSERT(p && IS_QUEEN(p));
    uColor = GET_COLOR(p);
    ASSERT(IS_VALID_COLOR(uColor));
    xColor = FLIP(uColor);
    ASSERT(IS_ON_BOARD(KingPosition(pos, xColor)));
    ASSERT(IS_KING(pos->rgSquare[KingPosition(pos, xColor)].pPiece));

    //
    // Queen mobility (and update attack tables) -- two single magic
    // probes (rook-direction + bishop-direction), unioned, then one
    // shared mask pass. No chain walk (see MOBILITY_BITBOARD_REWRITE.md):
    //   - terminal enemy queen/king: counts unconditionally -- a capture
    //     is always "real" mobility.
    //   - empty or terminal enemy pawn/minor/rook: counts unless the
    //     square is attacked by an enemy pawn, minor, rook, or (modulo
    //     our own defense) the enemy king -- same partition
    //     bishop/knight/rook's reductions use, just with a bigger
    //     "cheaper piece" set since the queen is the most valuable.
    //   - any friendly piece: blocks, no count.
    //
    // Deliberately NOT replicated: mobility credit for squares beyond a
    // friendly rook/bishop/queen battery partner -- a queen cannot
    // physically move past a piece it shares a square with in one ply,
    // so (same as bishop/rook) that was never "real mobility" to begin
    // with. Also NOT replicated, and needing no replacement: the old
    // code's x-ray-attack population. Unlike bishop/rook, queen's old
    // chain only ever continued through a FRIENDLY blocker (it never
    // x-rayed through any enemy piece at all -- QMOB_ENEMY_GE always
    // stopped the ray in the original mailbox table). By the same
    // redundancy argument used to drop bishop/rook's friendly-blocker
    // x-ray case, that information was always a duplicate of the
    // blocking piece's own direct-attack pass -- there's no enemy-GE
    // case here to replace, so _EvalKingSafety's queen-x-ray reads
    // (pos->bbQueenXrayAttacks[xColor]) see nothing lost by simply never
    // populating it.
    //
    BITBOARD bbEnemyOcc = _BuildFriendlySideBB(pos, xColor);
    BITBOARD bbAttackTotal = _RookAttacksBB(c, pos->bbOccupied) |
        _BishopAttacksBB(c, pos->bbOccupied);
    BITBOARD bbEnemyGEHere = bbAttackTotal & bbEnemyQK;
    BITBOARD bbEnemyLEHere = bbAttackTotal & bbEnemyOcc & ~bbEnemyGEHere;
    BITBOARD bbMobility = (bbAttackTotal & ~pos->bbOccupied & ~bbUnsafeForQueen) |
        bbEnemyGEHere |
        (bbEnemyLEHere & ~bbUnsafeForQueen);

    pos->bbQueenAttacks[uColor] |= bbAttackTotal;

    uTotalMobility = FastCountBits(bbMobility);
    ASSERT(uTotalMobility <= 27);
    EVAL_TERM(uColor,
              QUEEN,
              c,
              pos->iScore[uColor],
              QUEEN_MOBILITY_BY_SQUARES[uTotalMobility],
              "queen mobility");

    // Look for queens with no mobility who are under attack.  These
    // pieces are trapped!
    if (uTotalMobility == 0)
    {
        _RecordTrappedCandidate(pos, uColor, c, 0);
    }
}


static SCORE FORCEINLINE
_EvalKingSafety(IN POSITION *pos,
                IN const COOR c,
                IN const PAWN_HASH_ENTRY *pHash,
                IN SEARCHER_THREAD_CONTEXT *ctx,
                IN const ULONG uColor,
                IN const ULONG xColor,
                IN const BITBOARD bbRing)
/**

Routine description:

    Safety half of _EvalKing's 2026-10-06 safety-vs-activity split --
    see that function's header comment. Full ring-attack/danger-
    pattern scoring, file-storm defects (cached), stay-on-initial-
    square bonus, castling/development. Only called when the enemy
    has enough material (DO_KING_SAFETY_THRESHOLD) to make an attack
    worth scoring. FORCEINLINE: this and _EvalKingActivity are split
    out of _EvalKing purely for readability -- _EvalKing calls exactly
    one of the two per invocation (never both), so forcing both
    inline reproduces the exact same generated code as the old single
    monolithic function, not a real call.

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,
    SEARCHER_THREAD_CONTEXT *ctx,
    ULONG uColor,
    ULONG xColor,
    BITBOARD bbRing : g_KingAttacksBB[c], already computed by the caller

Return value:

    SCORE

**/
{
    BITV bvPattern;
    ULONG uQueenNearKing;
    SCORE iKingScore = 0;

    // 2026-09-15: linear-SCORE rewrite -- see king_safety_data/
    // HANDOFF.md's 2026-09-15 addendum for the full rationale. Replaces
    // the old shared uCounter -> KING_SAFETY_BY_COUNTER nonlinear-lookup
    // mechanism (EmptyAttackedSquare/EmptyUnattackedSquare/
    // OccupiedAttackedSquare/KingFlightDefects/KingSafetyDeltas/
    // KING_RING_IS_BACK all retired) with per-defect SCORE weights that
    // accumulate into one running total and get scaled by
    // REDUCED_MATERIAL_DOWN_SCALER exactly ONCE at the end -- by direct
    // instruction, since this is the hottest inner loop in eval.c and
    // scaler*(A+B+C+...) is one multiply instead of scaler*A + scaler*B
    // + ... Ring-square attack/defense/flight terms below are computed
    // via bitboard intersection + FastCountBits() against the whole front/
    // back/side bucket at once (g_KingRingFrontBB/g_KingRingBackBB/
    // g_KingRingSideBB, data.c), not a per-square branchy loop -- a
    // fixed handful of AND+popcount ops regardless of how many ring
    // squares are actually occupied/attacked.
    //
    // Magnitudes are the mate-mining logistic regression's cleaned,
    // collinearity-reduced coefficients (front_def/back_def/*_atk_queen
    // dropped -- collinear with the atk_* terms and queenproximity
    // respectively), unstandardized (divided by each raw feature's own
    // std-dev) and converted to centipawns via k =~ -14, the same
    // conversion constant KING_QUEEN_PROXIMITY_DANGER's self-play-
    // validated -14/count already established (anchor: validated weight
    // / that term's own cleaned raw coefficient). None of the NEW
    // per-piece-type/undefended/xray/flight terms below have been
    // through self-play yet as of this writing -- expect every one of
    // these starting magnitudes to move once tested, same discipline as
    // the file-storm and queenproximity retunes before them.
    //
    // 2026-09-15 (later): promoted from local statics to file scope
    // and DNA-registered (see g_EvalDNA below) so they can be Texel-
    // tuned directly against real game outcomes instead of hand-
    // translated from regression coefficients -- see king_safety_data/
    // HANDOFF.md's addendum on why the log-odds-to-centipawn
    // translation step was the likely source of this rewrite's
    // self-play regression, not the underlying feature signal itself.
    const ULONG uKingDangerAcceleratorBucketWidth = 56;

    // Depending on whether we are assessing a black or white king,
    // the "front" and "back" directions swap.  Front is "towards
    // the center of the board at game start time".
    BITBOARD bbFront = g_KingRingFrontBB[uColor][c];
    BITBOARD bbBack = g_KingRingBackBB[uColor][c];
    BITBOARD bbSide = g_KingRingSideBB[c];
    ASSERT(bbRing == (bbFront | bbBack | bbSide));

    BITBOARD bbEnemyAtkAny = pos->bbPawnAttacks[xColor] |
        pos->bbMinorAttacks[xColor] |
        pos->bbRookAttacks[xColor] |
        pos->bbQueenAttacks[xColor];
    BITBOARD bbEnemyXrayAny = pos->bbMinorXrayAttacks[xColor] |
        pos->bbRookXrayAttacks[xColor] |
        pos->bbQueenXrayAttacks[xColor];
    BITBOARD bbOwnDefendNoKing = pos->bbPawnAttacks[uColor] |
        pos->bbMinorAttacks[uColor] |
        pos->bbRookAttacks[uColor] |
        pos->bbQueenAttacks[uColor];
    BITBOARD bbEmpty = ~pos->bbOccupied;
    BITBOARD bbUndefended = bbEnemyAtkAny & ~bbOwnDefendNoKing;
    SCORE iSafety = 0;

    // Pay attention to the types of pieces currently attacking.
    bvPattern =
        (((pos->bbPawnAttacks[xColor] & bbRing) != 0) ? PAWN_BIT : 0) |
        ((((pos->bbMinorAttacks[xColor] | pos->bbMinorXrayAttacks[xColor]) &
           bbRing) != 0) ? MINOR_BIT : 0) |
        ((((pos->bbRookAttacks[xColor] | pos->bbRookXrayAttacks[xColor]) &
           bbRing) != 0) ? ROOK_BIT : 0) |
        ((((pos->bbQueenAttacks[xColor] | pos->bbQueenXrayAttacks[xColor]) &
           bbRing) != 0) ? QUEEN_BIT : 0);
    ASSERT(bvPattern < 32);
    iSafety += KING_ATTACK_PATTERN_SCALE *
        (SCORE)KING_COUNTER_BY_ATTACK_PATTERN[bvPattern];

    // Count how many ring squares are attacked by the enemy queen.
    // Note: we remove queen-king tropism bonus from EvalQueen in
    // favor of this.
    uQueenNearKing = FastCountBits(
        bbRing & (pos->bbQueenAttacks[xColor] | pos->bbQueenXrayAttacks[xColor])
    );
    ASSERT(uQueenNearKing <= 8);
    iSafety += KING_QUEEN_PROXIMITY_DANGER[MINU(uQueenNearKing, 6)];

    // Minor attacks at front, side, back.
    iSafety += KING_RING_ATTACK_MINOR[0] *
        (SCORE)FastCountBits(bbFront & pos->bbMinorAttacks[xColor]);
    iSafety += KING_RING_ATTACK_MINOR[1] *
        (SCORE)FastCountBits(bbBack & pos->bbMinorAttacks[xColor]);
    iSafety += KING_RING_ATTACK_MINOR[2] *
        (SCORE)FastCountBits(bbSide & pos->bbMinorAttacks[xColor]);

    // Rook attacks at front, side, back.
    iSafety += KING_RING_ATTACK_ROOK[0] *
        (SCORE)FastCountBits(bbFront & pos->bbRookAttacks[xColor]);
    iSafety += KING_RING_ATTACK_ROOK[1] *
        (SCORE)FastCountBits(bbBack & pos->bbRookAttacks[xColor]);
    iSafety += KING_RING_ATTACK_ROOK[2] *
        (SCORE)FastCountBits(bbSide & pos->bbRookAttacks[xColor]);

    // Pawn attacks.
    iSafety += KING_RING_ATTACK_PAWN *
        (SCORE)FastCountBits(bbRing & pos->bbPawnAttacks[xColor]);

    // Undefended squares in front, side, back.
    iSafety += KING_RING_UNDEFENDED[0] *
        (SCORE)FastCountBits(bbFront & bbUndefended);
    iSafety += KING_RING_UNDEFENDED[1] *
        (SCORE)FastCountBits(bbBack & bbUndefended);
    iSafety += KING_RING_UNDEFENDED[2] *
        (SCORE)FastCountBits(bbSide & bbUndefended);

    // Only xray attack, no direct attack.
    iSafety += KING_RING_XRAY_BONUS *
        (SCORE)FastCountBits(bbRing & bbEnemyXrayAny & ~bbEnemyAtkAny);

    // Flight squares are empty, unattacked squares around the king.
    // In front of the king, though, these are gaps and a negative
    // whereas behind the king they are legitimately small bonuses.
    iSafety += KING_RING_FRONT_FLIGHT_PENALTY *
        (SCORE)FastCountBits(bbFront & bbEmpty & ~bbEnemyAtkAny);

    // Small bonus for empty squares behind the king to retreat into.
    iSafety += KING_BACK_FLIGHT_BONUS *
        (SCORE)FastCountBits(bbBack & bbEmpty & ~bbEnemyAtkAny);

    // _ComputeFileStormDefects's comment.
    iSafety += _GetFileStormDefects(ctx, pos, pHash, uColor);
    iSafety += KING_INITIAL_LOCATION_SCALE * KING_EVAL_INITIAL_LOCATION[uColor][c];

    // Danger-magnitude acceleration -- see KING_DANGER_ACCELERATOR's
    // comment above. Applied here (as part of the real per-king
    // computation) rather than folded into the final material-scale
    // multiply below, since it's a function of the aggregate danger
    // itself, not of the attacker's material.
    if (iSafety < 0)
    {
        ULONG uMagBucket = MINU(6,
                                (ULONG)(-iSafety) / uKingDangerAcceleratorBucketWidth);
        iSafety = (iSafety * KING_DANGER_ACCELERATOR[uMagBucket]) / 128;
    }

#ifdef CALIBRATE_POSITIONAL
    // Restored 2026-09-15 (was dropped when the old uCounter/
    // KING_SAFETY_BY_COUNTER-shaped call site disappeared in the
    // linear-SCORE rewrite) -- see _RecordPositionalCalibration's
    // comment for why this now bins ABS(iSafety) instead of the old
    // always-nonnegative -i.
    _RecordPositionalCalibration(ctx, pos, pHash, uColor,
                                 (ULONG)((iSafety < 0) ? -iSafety : iSafety));
#endif

    // Single multiply for the entire accumulated total -- the
    // whole point of this rewrite (see the function-header comment
    // above). Note: can't use pos->iReducedMaterialDownScaler here
    // because we are scaling based on the _other_ side's material.
    iSafety = (iSafety *
               (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[xColor]]) / 8;
    EVAL_TERM(uColor,
              KING,
              c,
              iKingScore,
              iSafety,
              "king safety");

    // Bonus for castling / penalty for loss of castle.  Also, if
    // side has not yet castled AND castling is still a live
    // option, be concerned with undeveloped minor pieces.
    //
    // 2026-10-06: split the development penalty's gate from the
    // missing-castle-option penalty's -- they need different
    // conditions. Development should stop once the castling
    // decision is permanently settled, whether that's by
    // castling (the outer !fCastled check) or by losing both
    // rights without ever castling (not caught by that check
    // alone -- a side that never castles and never loses the
    // right would otherwise be flagged "undeveloped" forever).
    // The missing-castle-option penalty must do the opposite --
    // persist *after* a right is lost, not stop then -- since
    // its whole purpose is discouraging throwing the right away
    // in the first place; gating it the same way development is
    // gated would silently disable it exactly when it's supposed
    // to fire.
    //
    // Color-indexed instead of a WHITE/BLACK branch over two
    // copy-pasted blocks -- one fewer per-piece branch for the
    // processor to mispredict (board_representation/EVAL.md
    // section 9).
    ULONG uDevelopmentScaler = CASTLE_AND_DEVELOPMENT_SCALER[pos->uArmyScaler[uColor]];
    if (uDevelopmentScaler > 0)
    {
        static const BITV CASTLE_SHORT[2] =
            { CASTLE_BLACK_SHORT, CASTLE_WHITE_SHORT };
        static const BITV CASTLE_LONG[2] =
            { CASTLE_BLACK_LONG, CASTLE_WHITE_LONG };
        static const BITV bvBothRights[2] =
            { CASTLE_SHORT[BLACK] | CASTLE_LONG[BLACK],
              CASTLE_SHORT[WHITE] | CASTLE_LONG[WHITE] };

        ASSERT(pos->uMinorsAtHome[uColor] <= 4);
        EVAL_TERM(uColor,
                  0,
                  ILLEGAL_COOR,
                  pos->iScore[uColor],
                  (SCORE)((UNDEVELOPED_MINORS_IN_OPENING[pos->uMinorsAtHome[uColor]] *
                           (SCORE)uDevelopmentScaler) / 8),
                  "development");

        // One popcount answers both "can this side still
        // castle at all" (>0, gates development below) and
        // "how many options are missing" (2-count, scales
        // the persistent penalty below) -- replaces two
        // separate (==0) branches/multiplies/EVAL_TERM calls
        // with one shared count.
        ULONG uRightsRemaining =
            FastCountBits(pos->bvCastleInfo & bvBothRights[uColor]);
        ASSERT(uRightsRemaining <= 2);

        // Deliberately NOT gated on uRightsRemaining > 0 --
        // see this block's header comment. Fires at full
        // weight (both options gone) even long after the
        // rights were lost, for as long as uDevelopmentScaler
        // itself stays nonzero.
        EVAL_TERM(uColor,
                  KING,
                  c,
                  iKingScore,
                  (SCORE)(
                      (FALSE == pos->fCastled[uColor]) *
                      (KING_MISSING_ONE_CASTLE_OPTION *
                           (SCORE)(2 - uRightsRemaining) *
                           (SCORE)uDevelopmentScaler) / 8),
                  "missing castle option(s)");
    }
    return iKingScore;
}


static SCORE FORCEINLINE
_EvalKingActivity(IN POSITION *pos,
                  IN const COOR c,
                  IN const PAWN_HASH_ENTRY *pHash,
                  IN SEARCHER_THREAD_CONTEXT *ctx,
                  IN const ULONG uColor,
                  IN const ULONG xColor)
/**

Routine description:

    Activity half of _EvalKing's 2026-10-06 safety-vs-activity split --
    see that function's header comment. KING_TO_CENTER unconditionally;
    once the enemy is down to at most one non-king piece, the sharper
    passer-support/in-the-action guidance too. Only called when the
    enemy lacks mating material (below DO_KING_SAFETY_THRESHOLD).
    FORCEINLINE -- see _EvalKingSafety's comment for why this costs
    nothing over the old monolithic function.

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,
    SEARCHER_THREAD_CONTEXT *ctx,
    ULONG uColor,
    ULONG xColor

Return value:

    SCORE

**/
{
    SCORE i;
    SCORE iKingScore = 0;

    //
    // Come out. KING_TO_CENTER applies unconditionally (no longer
    // gated by uTotalNonPawnsBothSides<8 -- that was a different,
    // combined-both-sides unit than this whole split now uses, and
    // left a gap between "safety stops mattering" and "centralizing
    // is actually encouraged"; see _EvalKing's header comment).
    //
    i = KING_TO_CENTER[c];
    EVAL_TERM(uColor,
              KING,
              c,
              iKingScore,
              i,
              "centralize king");

    // Sharper late-game guidance once the enemy is down to at most
    // one non-king piece (lone king, K+minor, K+rook, even K+queen
    // -- though a lone queen's own material value already exceeds
    // DO_KING_SAFETY_THRESHOLD on its own, VALUE_QUEEN=975 >
    // VALUE_ROOK+VALUE_BISHOP=800, so that specific case can never
    // actually reach this function at all; the count check below is
    // correct on its own terms regardless). Per-call/per-king
    // (xColor's own material), not the old combined-both-sides
    // uTotalNonPawnsBothSides==2 -- the two kings' own enemies can
    // legitimately disagree now.
    if (TotalNonPawnCount(pos, xColor) <= 2)
    {
        // Supporting-own-passer and out-of-action-in-KP-endgames,
        // combined into one cached lookup (_GetKingActivityBonus)
        // -- both depend only on (pawn structure + this king's own
        // square), both only ever apply in this same branch, so
        // one key computation/hash probe serves both instead of
        // two. Trades away per-passer-square EVAL_TERM attribution
        // (EVAL_DUMP tracing only, not used in release builds) for
        // fewer instructions in the inner loop, by direct request
        // -- see git history for the old separated version if
        // finer dump granularity is ever needed again.
        i = _GetKingActivityBonus(ctx, pos, pHash, uColor, c);
        EVAL_TERM(uColor,
                  KING,
                  c,
                  iKingScore,
                  i,
                  "king activity (passer support + in/out of action)");
    }
    return iKingScore;
}


static void
_EvalKing(IN OUT POSITION *pos,
          IN const COOR c,
          IN const PAWN_HASH_ENTRY *pHash,
          IN SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    2026-10-06: restructured into an explicit safety-vs-activity split
    on pos->uNonPawnMaterial[xColor] (this king's own enemy's
    material) against DO_KING_SAFETY_THRESHOLD -- above it, stay
    hidden (_EvalKingSafety: full ring-attack/danger scoring, stay-
    on-initial-square bonus); below it, come out (_EvalKingActivity:
    KING_TO_CENTER unconditionally, plus, once the enemy is down to
    at most one non-king piece, the sharper passer-support/in-the-
    action guidance). Replaces the old `goto skip_safety` plus two
    *separate*, independently-thresholded gates (KEEP_KING_AT_HOME_
    THRESHOLD for the stay-home bonus, uTotalNonPawnsBothSides<8/==2
    -- a different, combined-both-sides unit -- for the endgame
    terms) that didn't line up with each other or with this one,
    leaving a dead band where safety was scored but neither a stay-
    home nor a come-out incentive applied. This single threshold now
    drives both halves, so the two outcomes are exact mirror images
    of one decision rather than three loosely related ones.

    Split into two FORCEINLINE helpers purely for readability -- see
    _EvalKingSafety's comment for why this costs nothing versus the
    old single monolithic function.

    No longer takes uTotalNonPawnsBothSides -- the old combined-both-
    sides gate it fed is gone, replaced by a per-call check
    (TotalNonPawnCount(pos, xColor), this king's own enemy only, not a
    hoisted both-sides sum), so there's no shared value left worth
    hoisting out to Eval().

Parameters:

    POSITION *pos,
    COOR c,
    PAWN_HASH_ENTRY *pHash,
    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    FLAG

**/
{
    PIECE p;
    ULONG uColor, xColor;
    ULONG u;
    SCORE iKingScore;

    ASSERT(IS_ON_BOARD(c));
    p = pos->rgSquare[c].pPiece;
    ASSERT(p && IS_KING(p));
    uColor = GET_COLOR(p);
    xColor = FLIP(uColor);
    ASSERT(IS_VALID_COLOR(uColor) && IS_VALID_COLOR(xColor));

    // Update attack bitvs for squares around the king.
    BITBOARD bbRing = g_KingAttacksBB[c];
    pos->bbKingAttacks[uColor] |= bbRing;

    // Safety-vs-activity split -- see this function's header comment
    // (2026-10-06 restructuring). Don't bother with king safety when
    // the other side has low material; instead, actively encourage
    // this king out.
    u = pos->uNonPawnMaterial[xColor];
    ASSERT(u >= VALUE_KING);
    if (u > DO_KING_SAFETY_THRESHOLD)
    {
        iKingScore = _EvalKingSafety(pos, c, pHash, ctx, uColor, xColor, bbRing);
    }
    else
    {
        iKingScore = _EvalKingActivity(pos, c, pHash, ctx, uColor, xColor);
    }
    pos->iScore[uColor] += iKingScore;
    ctx->sPlyInfo[ctx->uPly].iKingScore[uColor] = iKingScore;
}


static FLAG
_EvalUnstoppablePasser(IN OUT POSITION *pos)
/**

Routine description:

    True-knowledge replacement for _EvalPasserRacesAgainstLoneKings
    (below), used ONLY when both sides are pure king-and-pawns (both
    TotalNonPawnCount == 1) -- the exact KPvKP shape this session's
    investigation exhaustively verified. Calls the SAME shared,
    exhaustively-verified routines recogn.c's hard-bound KPvKP
    recognizer uses (IsUnstoppableLoneKingPasser for a true-lone-king
    opponent's any-rank square-rule race, HasStaticUnstoppablePasser for
    the general "opponent also has pawns" 7th/2nd-rank case), so there
    is exactly one implementation of "is this pawn unstoppable," not two
    that can silently diverge the way this file's old passer-race
    heuristic and recogn.c's KPK recognizer once did (the whole reason
    this investigation started).

    _EvalPasserRacesAgainstLoneKings's own precondition is looser (fires
    whenever EITHER side is bare, even if the OTHER side still has real
    pieces, e.g. K+R+P vs K) -- that broader shape was never covered by
    this session's KPvKP work and is NOT provably safe for the
    shared routines here (their reasoning assumes no other pieces exist
    to interpose/defend/escape), so the call site below keeps routing
    that case to the old function unchanged.

    Returns whether it actually placed a credit for either side. This
    function is trustworthy but narrow -- it only ever fires for the
    true-lone-king sub-case of pure KPvKP, and stays silent (returns
    FALSE) for the "both sides still have pawns" sub-case rather than
    guess. The caller uses this to fall back to
    _EvalPasserRacesAgainstLoneKings (dodgy but broader-coverage) only
    when this function had nothing to say, instead of losing that
    coverage outright.

Parameters:

    POSITION *pos

Return value:

    FLAG -- TRUE if a credit was placed for either side

**/
{
    ULONG uColor;
    FLAG fFired = FALSE;

    FOREACH_COLOR(uColor)
    {
        ULONG xColor = FLIP(uColor);
        COOR c;

        if (0 == FastCountBits(pos->bbPawns[uColor]))
        {
            continue;
        }

        if (0 == FastCountBits(pos->bbPawns[xColor]))
        {
            // True lone-king opponent: the general "rule of the
            // square + king escort" race, any rank, not just the
            // 7th/2nd -- see IsUnstoppableLoneKingPasser's own header
            // comment (0 wrong across all 165,676 EGTB-covered legal
            // single-pawn KPK positions).
            BITBOARD bb = pos->bbPawns[uColor];
            while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb)))
            {
                if (TRUE == IsUnstoppableLoneKingPasser(pos, uColor, c))
                {
                    EVAL_TERM(uColor,
                              PAWN,
                              c,
                              pos->iScore[uColor],
                              RACER_WINS_RACE,
                              "unstoppable passer (lone king)");
                    fFired = TRUE;
                    //
                    // break, not return: uColor is done (one credit is
                    // enough for this side), but the OTHER color still
                    // needs to be checked by this same FOREACH_COLOR
                    // loop -- an earlier version of this function
                    // returned here, which meant whichever color
                    // happened to be checked first (by FOREACH_COLOR's
                    // iteration order) silently suppressed any check of
                    // the other side at all, even a far more urgent
                    // threat. Found via a real regression: White's Ph7
                    // one push from queening
                    // (8/7P/6p1/3k1p2/2p5/3pK3/8/8 w - -, this whole
                    // investigation's original motivating position)
                    // scored -6.09 (the exact ORIGINAL buggy value from
                    // before this session) because Black's much weaker
                    // d3 pawn got checked first and its credit's early
                    // return meant White's real threat was never
                    // evaluated at all.
                    //
                    break;
                }
            }
        }
        //
        // Deliberately nothing here for "opponent also has pawns."
        // A prior session (see the stashed 2026-09-2x eval.c/recogn.c
        // "passer-race + king-escort rework") tried exactly this
        // extension, measured it at only ~1% wrong-side rate against
        // EGTB, and STILL found it caused a real playing-strength
        // regression in overnight self-play -- a low measured
        // false-positive rate doesn't guarantee an eval nudge is
        // actually good for play; it can still systematically mislead
        // move choice/ordering in ways a raw error-rate number doesn't
        // capture. That session's own conclusion (matched here rather
        // than re-litigated): restrict this function to the exact same
        // true-lone-king precondition recogn.c's own hard bound
        // trusts, and leave the "both sides have pawns" case to
        // recogn.c's search-time recognizer (_RecognizeKPK) and plain
        // positional eval terms, not a duplicate heuristic here. An
        // eval.c attempt at this (HasRacingUnstoppablePasser) was
        // built and measured this session before finding this same
        // prior-session lesson -- removed rather than kept as unused
        // dead code; see git history if this is ever revisited with a
        // real self-play test to back it, not just an EGTB sample.
        //
    }

    return(fFired);
}


FLAG
_EvalPasserRacesAgainstLoneKings(IN OUT SEARCHER_THREAD_CONTEXT *ctx,
                                 IN PAWN_HASH_ENTRY *pHash)
/**

Routine description:

    Determine if one side has a pawn that is unstoppable.

    This always works for KPK or KPKP but gets dodgy if a side has
    more than 1 pawn.  Error rates on KPPKPP are ~5% and KPKPPP
    are ~1%.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx,
    PAWN_HASH_ENTRY *pHash,

Return value:

    void

**/
{
    BITBOARD bb[2];
    ULONG uColor, xColor;
    int d1;
    COOR cKing[2];
    COOR c, cQueen;
    ULONG uEnemyKingDist, uPawnDist, uFriendKingDist;
    ULONG uMinRacerDist[2] = {99, 99};
    ULONG uMovesSpent[2];
    FLAG fDontCountMeOut[2];

    POSITION *pos = &ctx->sPosition;

    // Don't recognize if stm is in check.
    PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
    if (pi->fInCheck)
    {
        return(FALSE);
    }

    // Only deal with positions that have passers.
    bb[BLACK] = pHash->bbPasserLocations[BLACK];
    bb[WHITE] = pHash->bbPasserLocations[WHITE];
    if (!(bb[BLACK] | bb[WHITE]))
    {
        return(FALSE);
    }
    ASSERT((TotalNonPawnCount(pos, WHITE) == 1) || (TotalNonPawnCount(pos, BLACK) == 1));

    // Don't make a call if the king is well placed and the side has
    // pawns left.
    fDontCountMeOut[BLACK] = ((RANK(KingPosition(pos, BLACK)) <= 3) &&
                              (pos->bbPawns[BLACK] != 0));
    fDontCountMeOut[WHITE] = ((RANK(KingPosition(pos, WHITE)) >= 6) &&
                              (pos->bbPawns[WHITE] != 0));

    cKing[WHITE] = KingPosition(pos, WHITE);
    ASSERT(IS_KING(pos->rgSquare[cKing[WHITE]].pPiece));
    ASSERT(GET_COLOR(pos->rgSquare[cKing[WHITE]].pPiece) == WHITE);
    cKing[BLACK] = KingPosition(pos, BLACK);
    ASSERT(IS_KING(pos->rgSquare[cKing[BLACK]].pPiece));
    ASSERT(GET_COLOR(pos->rgSquare[cKing[BLACK]].pPiece) == BLACK);

    FOREACH_COLOR(uColor)
    {
        // If uColor has no passers, skip it.
        if (!bb[uColor])
        {
            continue;
        }

        // If xColor has any piece other than a king (and maybe some pawns), skip.
        xColor = FLIP(uColor);
        if (TotalNonPawnCount(pos, xColor) != 1)
        {
            continue;
        }
        d1 = 16 * g_iAhead[uColor];

        uMovesSpent[uColor] = 1;
        uMovesSpent[xColor] = 0;
        while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(
                              &(bb[uColor]))))
        {
            // If this pawn is right next to the enemy king, don't
            // predict the number of moves it takes to queen.
            if (xColor == pos->uToMove &&
                (DISTANCE(cKing[xColor], c) == 1) &&
                (DISTANCE(cKing[uColor], c) != 1))
            {
                uMovesSpent[xColor] += 1;
                continue;
            }
            fDontCountMeOut[uColor] = TRUE;

            cQueen = FILE_RANK_TO_COOR(FILE(c), QUEENING_RANK[uColor]);
            ASSERT(FILE(cQueen) == FILE(c));

            // Don't call rook pawn races with the friendly king in a
            // dodgy position.
            if (((A == FILE(c)) || (H == FILE(c))) &&
                (FILE(c) == FILE(cKing[uColor])) &&
                (0 == DISTANCE(cKing[uColor], cQueen)))
            {
                continue;
            }

            uPawnDist = RANK_DISTANCE(cQueen, c);
            uPawnDist -= ((RANK(c) == JUMPING_RANK[uColor]) &&
                          (IS_EMPTY(pos->rgSquare[c + d1].pPiece) &&
                           IS_EMPTY(pos->rgSquare[c + d1 * 2].pPiece)));
            ASSERT((uPawnDist >= 1) && (uPawnDist <= 6));
            uPawnDist += uMovesSpent[uColor];

            // Rule of the square; can this passer make it to
            // the queening square before the enemy king?
            uEnemyKingDist = DISTANCE(cKing[xColor], cQueen);
            if (uEnemyKingDist > 0)
            {
                uEnemyKingDist -= (pos->uToMove == xColor);
            }
            ASSERT((uEnemyKingDist >= 0) && (uPawnDist <= 7));
            if (uPawnDist < uEnemyKingDist)
            {
                uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor], uPawnDist);
            }

            // See if the friend king can escort this passer in. Same-
            // file adjacency alone doesn't distinguish a king BEHIND
            // the pawn (genuine escort) from a king sitting on the
            // very next square in front of it, i.e. cKing[uColor] ==
            // c + d1 (blocking its own pawn's path, not helping it) --
            // found via an exhaustive KPvKP/EGTB cross-check
            // (8/8/8/8/8/6Pp/7k/5K2 b - -: Black king h2 sits directly
            // in front of its own h3 pawn, yet this branch credited an
            // escort bonus as if h2 were behind it). Exclude that
            // square explicitly rather than just checking direction,
            // since it's the one same-file square DISTANCE<=1 permits
            // that unambiguously blocks rather than escorts.
            uFriendKingDist = DISTANCE(cKing[uColor], cQueen);
            if ((uFriendKingDist <= 1) && (DISTANCE(cKing[uColor], c) <= 1))
            {
                if (FILE(c) != FILE(cKing[uColor]))
                {
                    uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor],
                                                 uPawnDist);
                }
                else if ((cKing[uColor] != (c + d1)) &&
                         (FILE(cKing[xColor]) != A) &&
                         (FILE(cKing[xColor]) != H))
                {
                    uMinRacerDist[uColor] = MINU(uMinRacerDist[uColor],
                                                 (uPawnDist + 1));
                }
            }
        }

        // uMovesSpent[xColor] counts how many of uColor's OWN passers
        // just got individually skipped above as "adjacent to xColor's
        // king, xColor to move -- assume it's captured for free." Fine
        // when it happens to exactly one pawn, but when it happens to
        // TWO OR MORE, xColor's king is adjacent to multiple of
        // uColor's passers at once and can only actually capture ONE
        // of them -- the classic king-overload fork (found via random
        // KPPKPP/KPKPPP sampling against EGTB:
        // 8/5P2/1k6/8/8/8/pKp2P2/8 w - -, White king b2 flanked by
        // Black's a2 and c2, each one square from queening -- White
        // captures one, Black queens the other, Black wins by force,
        // but the per-pawn skip above silently dropped BOTH of
        // Black's passers from consideration, crediting White's own
        // ordinary race instead). This function's per-pawn model has
        // no way to actually resolve a fork like this ("TODO: winning
        // connected passers" above already flags the general
        // connected-passer gap as out of scope) -- the safe, precision-
        // over-recall response is not to guess who really wins, but to
        // stop trusting THE OTHER side's credit here, the same way
        // fDontCountMeOut already protects a side with real drawing
        // chances elsewhere in this function.
        if (uMovesSpent[xColor] >= 2)
        {
            fDontCountMeOut[uColor] = TRUE;
        }
    }

    if ((uMinRacerDist[WHITE] < uMinRacerDist[BLACK]) &&
        (FALSE == fDontCountMeOut[BLACK]))
    {
        EVAL_TERM(WHITE,
                  PAWN,
                  ILLEGAL_COOR,
                  pos->iScore[WHITE],
                  RACER_WINS_RACE - uMinRacerDist[WHITE] * 4,
                  "winning racer pawn");
        return(TRUE);
    }
    else if ((uMinRacerDist[BLACK] < uMinRacerDist[WHITE]) &&
             (FALSE == fDontCountMeOut[WHITE]))
    {
        EVAL_TERM(BLACK,
                  PAWN,
                  ILLEGAL_COOR,
                  pos->iScore[BLACK],
                  RACER_WINS_RACE - uMinRacerDist[BLACK] * 4,
                  "winning racer pawn");
        return(TRUE);
    }
    return(FALSE);
}


static void
_ReEvalPassers(IN OUT POSITION *pos,
             IN PAWN_HASH_ENTRY *pHash)
/**

Routine description:

Parameters:

    POSITION *pos,
    PAWN_HASH_ENTRY *pHash,

Return value:

    void

**/
{
    ULONG u;
    ULONG uColor;
    ULONG xColor;
    COOR c;
    COOR cSquare;
    BITBOARD bb;
    PIECE p;
    SCORE i;
    ULONG uNumPassers[2] = { 0, 0 };
    int d1;

    ASSERT(pHash->bbPasserLocations[WHITE] |
           pHash->bbPasserLocations[BLACK]);

    FOREACH_COLOR(uColor)
    {
        xColor = FLIP(uColor);
        bb = pHash->bbPasserLocations[uColor];
        if (bb != 0)
        {
            uNumPassers[uColor] = FastCountBits(bb);
            ASSERT(uNumPassers[uColor] > 0);
            d1 = 16 * g_iAhead[uColor];
            ASSERT((d1 * 2) == (32 * g_iAhead[uColor]));

            while(IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bb)))
            {
                //
                // Consider the control of the square in front of the passer
                //
                cSquare = c + d1;
                ASSERT(IS_ON_BOARD(cSquare));
                u = _WhoControlsSquareFast(pos, cSquare);
                if (u == xColor)
                {
                    EVAL_TERM(uColor,
                              PAWN,
                              c,
                              pos->iScore[uColor],
                              -((PASSER_BY_RANK[uColor][RANK(c)] / 4) +
                                (PASSER_BY_RANK[uColor][RANK(c)] / 16)),
                              "enemy controls sq ahead");
                }
                else if (u == (ULONG)-1)
                {
                    p = pos->rgSquare[cSquare].pPiece;
                    if (!IS_EMPTY(p) && (OPPOSITE_COLORS(p, uColor)))
                    {
                        ASSERT(GET_COLOR(p) != uColor);
                        EVAL_TERM(uColor,
                                  PAWN,
                                  c,
                                  pos->iScore[uColor],
                                  -(PASSER_BY_RANK[uColor][RANK(c)] / 4),
                                  "enemy occupies sq ahead");
                    }
                }
#ifdef DEBUG
                else
                {
                    ASSERT(u == uColor);
                }
#endif

                //
                // Consider distance from friend king / enemy king
                //
                i = (8 - DISTANCE(c, KingPosition(pos, uColor)));
                if (((uColor == WHITE) &&
                     ((KingPosition(pos, BLACK) >> 4) <= (c >> 4))) ||
                    ((uColor == BLACK) &&
                     ((KingPosition(pos, WHITE) >> 4) >= (c >> 4)))) {
                    //
                    // The enemy king is ahead of the passer
                    //
                    i += FILE_DISTANCE(c, KingPosition(pos, xColor)) * 4;
                }
                else
                {
                    //
                    // The enemy king is behind the passer
                    //
                    i += 10 + DISTANCE(c, KingPosition(pos, xColor)) * 4;
                }
                i *= PASSER_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]];
                i /= 8;
                EVAL_TERM(uColor,
                          PAWN,
                          c,
                          pos->iScore[uColor],
                          i,
                          "passer distance to kings");

                //
                // If a side is a piece down then the other side's passers
                // are even more dangerous.
                //
                if (TotalNonPawnCount(pos, uColor) >
                    TotalNonPawnCount(pos, xColor))
                {
                    i = (PASSER_BY_RANK[uColor][RANK(c)] / 2);
                    EVAL_TERM(uColor,
                              PAWN,
                              c,
                              pos->iScore[uColor],
                              i,
                              "passer and piece up");
                }

                //
                // TODO: For connected passers vs KR, consult the oracle
                //
            }
        }
    }

    //
    // Game stage bonus
    //
    u = pos->uArmyScaler[BLACK];
    EVAL_TERM(WHITE,
              PAWN,
              ILLEGAL_COOR,
              pos->iScore[WHITE],
              (uNumPassers[WHITE] * PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] * MULTIPLE_PASSER_SCALER[uNumPassers[WHITE]]) >> 5,
              "passer value material");
    ASSERT(PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] >= 0);
    u = pos->uArmyScaler[WHITE];
    EVAL_TERM(BLACK,
              PAWN,
              ILLEGAL_COOR,
              pos->iScore[BLACK],
              (uNumPassers[BLACK] * PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] * MULTIPLE_PASSER_SCALER[uNumPassers[BLACK]]) >> 5,
              "passer value material");
    ASSERT(PASSER_BONUS_AS_MATERIAL_COMES_OFF[u] >= 0);
}


static void
_EvalBadTrades(IN OUT POSITION *pos)
/**

Routine description:

Parameters:

    POSITION *pos,

Return value:

    void

**/
{
    ASSERT(pos->uNonPawnMaterial[WHITE] != pos->uNonPawnMaterial[BLACK]);
    ULONG uAhead = (pos->uNonPawnMaterial[WHITE] > pos->uNonPawnMaterial[BLACK]);
    ULONG uBehind = FLIP(uAhead);
#ifdef DEBUG
    if (pos->uNonPawnMaterial[WHITE] > pos->uNonPawnMaterial[BLACK])
    {
        ASSERT(uAhead == WHITE);
        ASSERT(uBehind == BLACK);
    }
    else
    {
        ASSERT(pos->uNonPawnMaterial[BLACK] > pos->uNonPawnMaterial[WHITE]);
        ASSERT(uAhead == BLACK);
        ASSERT(uBehind == WHITE);
    }
#endif

    //
    // A material-VALUE imbalance (uNonPawnMaterial differing, the
    // caller's gate) is not the same fact as a piece-COUNT imbalance --
    // e.g. 2R vs R+N is "up the exchange" with equal piece count on
    // both sides, not a side that has simplified/traded down to fewer
    // pieces. Ported from a stashed, previously-uncommitted eval.c
    // change (2026-09-2x eval audit session) -- mirrors Crafty's
    // EvaluateMaterial (~/crafty/evaluate.c), whose bad_trade bonus
    // explicitly requires Abs(occupied_count_diff) != 2 &&
    // occupied_count_diff != 0, i.e. it never fires when piece counts
    // are equal, deliberately leaving pure up-the-exchange positions to
    // ordinary material valuation instead of this term. Without this
    // check, typhoon double-counts: real, up-the-exchange credit
    // already exists via material value, and this term used to stack
    // an unconditional extra "keep trading" bonus on top regardless of
    // whether uAhead had actually traded down to fewer pieces at all --
    // found via the original eval audit
    // (8/2r4p/8/5p1R/8/1n4P1/1pk2PKP/4R3 b, 2R vs R+N, equal piece
    // count: typhoon +2.07 for White, Crafty -1.63 for White --
    // opposite sign, traced to this exact double-count).
    //
    if (TotalNonPawnCount(pos, uAhead) == TotalNonPawnCount(pos, uBehind))
    {
        return;
    }

    //
    // Encourage the side that is ahead in piece material to continue
    // trading pieces and not to trade pawns.  This also has the
    // effect of making the side that is behind in material want to
    // trade pawns and not pieces.  This also gives the side that is
    // ahead a bit of a "bad trade" bonus.  Note that the bonus is not
    // given if the side "ahead" has no pawns AND no mating material of
    // its own; this is so that the engine will not like positions like
    // KNB vs KRP - the side with the pawn has the winning chances.
    //
    ULONG uAheadPawnCount = FastCountBits(pos->bbPawns[uAhead]);
    ULONG uInverseBehindPieceCount = 11 - MINU(9, TotalNonPawnCount(pos, uBehind));
    //
    // "No mating material" here means the SAME lone-minor-piece test
    // SideHasWinningChances (above) already uses: king + exactly one
    // knight/bishop and nothing else -- a K+N or K+B can never force
    // mate alone, which is the actual KNB-vs-KRP failure mode this
    // whole guard exists for. Found via a real counterexample
    // (2k5/4r3/KP2P3/P7/7P/8/8/8 b - -): Black is ahead in non-pawn
    // material with a ROOK, not a lone minor -- a rook can genuinely
    // blockade/pick off multiple passed pawns on its own, nothing like
    // the KNB-vs-KRP case this guard was built for -- yet the old
    // "zero pawns -> zero bonus" version zeroed this out unconditionally
    // by piece count alone, silencing exactly the term that should
    // have been pushing back against White's four separately-scored
    // passed pawns.
    //
    FLAG fAheadLoneMinorNoMate =
        (2 == TotalNonPawnCount(pos, uAhead)) &&
        (1 == (FastCountBits(pos->bbPieces[uAhead][KNIGHT]) +
               FastCountBits(pos->bbPieces[uAhead][BISHOP])));
    EVAL_TERM(uAhead,
              0,
              ILLEGAL_COOR,
              pos->iScore[uAhead],
              (uInverseBehindPieceCount * 16) *
                  ((uAheadPawnCount != 0) || (FALSE == fAheadLoneMinorNoMate)),
              "trade pieces");
    // Zero pawns AND no mating material for the ahead side is the
    // classic false-positive (KNB vs KRP, minor-up-no-pawns endings
    // that are often drawn or even lost) -- the old DONT_TRADE_PAWNS
    // table existed specifically to punish it (-43/-10 depending on
    // lead size) rather than just trailing off toward a small positive
    // number. Keep that guard as a cheap branch rather than a lookup
    // table; the positive slope for 1+ pawns doesn't need the same
    // care. Same mating-material exception as "trade pieces" above:
    // zero pawns with REAL mating material (a rook, say) isn't the
    // KNB-vs-KRP failure mode this -30 penalty exists for, so it gets
    // a neutral 0 instead of being punished.
    EVAL_TERM(uAhead,
              0,
              ILLEGAL_COOR,
              pos->iScore[uAhead],
              (0 != uAheadPawnCount) ? (SCORE)(uAheadPawnCount * 2) :
                  (TRUE == fAheadLoneMinorNoMate) ? -30 : 0,
              "don't trade pawns");
}

#if 0
static void
_EvalLookForDanger(IN OUT SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

    This routine looks for squares on the board where the side to move
    has a piece that is en prise.  So far in eval we will have tagged
    pieces in situations where they are attacked by lesser-valued
    enemy pieces as "in danger".  However, because of the order in
    which the attack table was generated, we will have missed
    situations where a piece is undefended (or underdefended) and
    attacked by an enemy piece that is the same (or greater) value.

    Note: This routine only considers side to move.

    Also Note: this routine does not find pawns that are en prise, only
    pieces.

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    void

**/
{
    COOR c;
    BITBOARD bbNonKingPieces;
    POSITION *pos = &ctx->sPosition;
    ULONG uSide = pos->uToMove;
#ifdef DEBUG
    PIECE p;
#endif

    bbNonKingPieces = NON_KING_PIECES_BB(pos, uSide);
    while (IS_ON_BOARD(c = CoorFromBitBoardRank8ToRank1(&bbNonKingPieces)))
    {
#ifdef DEBUG
        ASSERT(IS_ON_BOARD(c));
        p = pos->rgSquare[c].pPiece;
        ASSERT(p);
        ASSERT(GET_COLOR(p) == uSide);
        ASSERT(!IS_PAWN(p));
#endif
        if (_WhoControlsSquareFast(pos, c) == FLIP(uSide))
        {
            RecordEnprisePiece(ctx, c);
        }
    }
}
#endif


static void
_EvalTrappedPieces(IN OUT SEARCHER_THREAD_CONTEXT *ctx)
/**

Routine description:

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx

Return value:

    static void

**/
{
    COOR c;
    COOR cBestOwnTrapped;
    ULONG uBestOwnTrappedValue;
    ULONG uColor;
    ULONG xColor;
    ULONG u;
    ULONG uFinalMobility;
    BITBOARD bbOwnDefend;
    BITBOARD bbUnsafeNow;
    BITBOARD bbStillSafe;
    POSITION *pos = &ctx->sPosition;
    PIECE p;
    SCORE i;

    FOREACH_COLOR(uColor)
    {
        xColor = FLIP(uColor);
        cBestOwnTrapped = ILLEGAL_COOR;
        uBestOwnTrappedValue = 0;
        for (u = 0; u < pos->uNumTrapped[uColor]; u++)
        {
            c = pos->cTrapped[uColor][u];
            ASSERT(IS_ON_BOARD(c));
            p = pos->rgSquare[c].pPiece;
#ifdef DEBUG
            ASSERT(p);
            ASSERT(!IS_PAWN(p));
            ASSERT(GET_COLOR(p) == uColor);
#endif

            // A nonzero bbTrappedEscapes snapshot means this candidate
            // was genuinely deferred (a bishop/knight/rook nominated at
            // low-but-nonzero partial-information mobility -- see
            // EVAL_MOBILITY_CAREFULLY_BELOW's comment) and is still
            // owed both its real mobility score (skipped at nomination
            // time) and a final trapped/not-trapped verdict, now that
            // every piece type -- including the enemy king -- has
            // contributed to the attack tables. A zero snapshot means
            // either a genuinely 0-mobility piece (already scored
            // inline, nothing left to re-derive -- see _EvalBishop's
            // comment on why those are never deferred) or a queen
            // (never deferred at all -- its own eval pass already runs
            // after every smaller piece type, so it doesn't have this
            // partial-information problem in the first place; see
            // _EvalQueen's bbUnsafeForQueen).
            if (pos->bbTrappedEscapes[uColor][u] != 0)
            {
                // bbOwnDefend excludes the candidate's own piece-type
                // bucket: bbMinorAttacks/bbRookAttacks already include
                // this very piece's own attack squares (populated
                // unconditionally before the nomination decision),
                // which are exactly its candidate escape squares --
                // crediting that back as "defense" would be circular (a
                // piece can't defend the square it would occupy after
                // moving off its own square). Conservative side effect:
                // a genuinely different friendly minor/rook defending
                // the same square as a trapped minor/rook is also
                // excluded, since the merged bitboards can't
                // distinguish "this piece" from "another piece of the
                // same bucket" -- known limitation, not fixed here.
                bbOwnDefend = pos->bbPawnAttacks[uColor] |
                              pos->bbQueenAttacks[uColor];
                if (!IS_BISHOP(p) && !IS_KNIGHT(p))
                {
                    bbOwnDefend |= pos->bbMinorAttacks[uColor];
                }
                if (!IS_ROOK(p))
                {
                    bbOwnDefend |= pos->bbRookAttacks[uColor];
                }

                // The only thing nomination-time couldn't see: the
                // enemy king's own attacks (pos->bbKingAttacks[xColor]
                // -- both kings have finished evaluating well before
                // _EvalTrappedPieces runs, see Eval()'s call order).
                // Everything else a candidate square could be unsafe
                // for (a cheaper enemy piece attacking it) was already
                // known and excluded at nomination time -- see
                // EVAL_MOBILITY_CAREFULLY_BELOW's comment.
                bbUnsafeNow = pos->bbKingAttacks[xColor] & ~bbOwnDefend;
                bbStillSafe = pos->bbTrappedEscapes[uColor][u] & ~bbUnsafeNow;
                uFinalMobility = FastCountBits(bbStillSafe);

                if (IS_BISHOP(p))
                {
                    EVAL_TERM(uColor, BISHOP, c, pos->iScore[uColor],
                              BISHOP_MOBILITY_BY_SQUARES[uFinalMobility],
                              "bishop mobility (deferred)");
                }
                else if (IS_KNIGHT(p))
                {
                    EVAL_TERM(uColor, KNIGHT, c, pos->iScore[uColor],
                              KNIGHT_MOBILITY_BY_COUNT[uFinalMobility],
                              "knight mobility (deferred)");
                }
                else if (IS_ROOK(p))
                {
                    ASSERT(pos->uArmyScaler[xColor] <= 31);
                    i = ROOK_MOBILITY_BY_SQUARES[uFinalMobility];
                    i *= (int)(REDUCED_MATERIAL_UP_SCALER[pos->uArmyScaler[xColor]] + 1);
                    i /= 8;
                    EVAL_TERM(uColor, ROOK, c, pos->iScore[uColor], i,
                              "rook mobility (deferred)");
                }

                if (bbStillSafe != 0)
                {
                    // A real escape exists once full attack information
                    // is in -- the loose, partial-information nomination
                    // was a false alarm, not actually trapped. Its
                    // (corrected, lower) mobility score was already
                    // banked above; nothing more to do for it.
                    continue;
                }
            }

            if (_WhoControlsSquareFast(pos, c) == xColor)
            {
                // See if the side who created the trap and controls
                // the square the trapped piece is sitting on has the
                // move too.  If so, uColor moved at ply-1.
                if (OPPOSITE_COLORS(uColor, pos->uToMove))
                {
                    if (ctx->uPly > 0)
                    {
                        RecordEnprisePieceAtPly(ctx, ctx->uPly - 1, c);
                    }
                    EVAL_TERM(uColor, p, c, pos->iScore[uColor],
                              ENPRISE_AND_TRAPPED_PENALTY,
                              "en prise and trapped");
                }

                // ctx->cTrapped[uPly] (RecordTrappedPiece's target)
                // is a single slot, not a list -- if more than one
                // of our own pieces is genuinely trapped this ply,
                // only report the most valuable one.
                else
                {
                    if (PIECE_VALUE(pos->rgSquare[c].pPiece) >
                        uBestOwnTrappedValue)
                    {
                        uBestOwnTrappedValue =
                            PIECE_VALUE(pos->rgSquare[c].pPiece);
                        cBestOwnTrapped = c;
                    }
                }
            }
        }

        // uColor has the move but we found at least one piece that
        // seems to have no safe place to move and is actively under
        // attack now.  It may not be lost, at least uColor has the
        // move.  But this is still a bad thing.
        if (IS_ON_BOARD(cBestOwnTrapped))
        {
            RecordTrappedPiece(ctx, cBestOwnTrapped);
            p = pos->rgSquare[cBestOwnTrapped].pPiece;
            EVAL_TERM(uColor, p, cBestOwnTrapped, pos->iScore[uColor],
                      TRAPPED_WITH_MOVE_PENALTY,
                      "trapped piece, our move");
        }
    }
}


static void
_EvalBishopPairs(IN POSITION *pos)
/*++

Routine description:

    Give a flat bonus to sides that have a viable bishop pair (one
    light-squared, one dark-squared) -- not scaled by pawn count, by
    direct instruction (2026-09-06).

Parameters:

    IN POSITION *pos - position

Return value:

    static void

--*/
{
    ULONG uColor;
    FOREACH_COLOR(uColor)
    {
        ULONG uBishopCount = FastCountBits(pos->bbPieces[uColor][BISHOP]);
        ASSERT(uBishopCount <= 10);
        ULONG uWhiteSqBishopCount = WhiteSqBishopCount(pos, uColor);
        ASSERT(uWhiteSqBishopCount <= 10);
        FLAG fPair = ((uBishopCount > 1) &
                      (uWhiteSqBishopCount != 0) &
                      (uWhiteSqBishopCount != uBishopCount));
        EVAL_TERM(uColor,
                  0,
                  ILLEGAL_COOR,
                  pos->iScore[uColor],
                  fPair * BISHOP_PAIR_BONUS,
                  "bishop pair");
    }
}


FLAG FORCEINLINE
SideHasWinningChances(IN POSITION *pos,
                      IN ULONG uColor)
/**

Routine description:

    Cheap, material-count-only classifier (the same idea as Crafty's
    EvaluateWinningChances): can uSide possibly force a win from this
    material alone, ignoring the actual position entirely? Used only
    to soften (scale toward drawscore) an otherwise-misleading raw
    material lead in Eval() below -- unlike recogn.c's interior-node
    recognizers (RECOGN_EXACT/UPPER/LOWER), this is never a hard claim
    fed into a search bound, so a wrong answer here just biases the
    eval a little; it can't corrupt alpha-beta the way a wrong hard
    recognizer bound can (see recogn.c's _RecognizeKNKP/_RecognizeKBNK
    incident).

    Deliberately conservative: mostly covers material shapes where "no,
    this can't be forced" is basic, textbook chess knowledge
    (insufficient mating material, up the exchange with nothing else
    changed, bare knights vs a bare king). One exception that DOES need
    real board information, not just material counts, is included below
    (wrong-bishop-pawn-with-king-in-time) precisely because it's common
    enough and cheap enough to be worth it; anything else needing real
    board geometry is recogn.c's hard-recognizer territory (already
    exact for tiny material there) or plain search's job, not this
    cheap pre-check's.

Parameters:

    POSITION *pos,
    ULONG uSide

Return value:

    static FLAG : TRUE if uSide has any winning chances at all, FALSE
        if this exact material can provably never be forced to a win
        regardless of position.

**/
{
    ULONG xColor = FLIP(uColor);
    ASSERT(IS_VALID_COLOR(uColor) && IS_VALID_COLOR(xColor));
    INT iMajorDiff;
    INT iMinorDiff;
    ULONG uColorKnights;
    ULONG uColorBishops = FastCountBits(pos->bbPieces[uColor][BISHOP]);

    // Wrong-bishop rook-pawn fortress: a lone bishop + rook-pawn(s) (all
    // on the A- or H-file), with the bishop unable to control the
    // promotion square, is a known draw once the defending bare king
    // can reach the corner in time -- regardless of how much raw pawn
    // material uSide has. Checked before the blanket "any pawn -> TRUE"
    // return below, which would otherwise hide this case entirely.
    // Mirrors Crafty's EvaluateWinningChances (~/crafty/evaluate.c) --
    // "in time" uses the same tempo-adjusted Chebyshev distance Crafty
    // uses (one square of credit to the defender if it's their move).
    // Ported from a stashed, previously-uncommitted eval.c change
    // (2026-09-2x eval audit session); testing methodology for its
    // false-positive rate against this session's own KP+KP* EGTB
    // harness is still to be built (see testeval.c/testrecogn.c) before
    // trusting the ~2.12% figure the stash's own comment cited -- that
    // number was never independently re-verified in this session. Only
    // ever softens a score (via EvalLookForDrawishSituations' /16
    // shrink), never used as a search-terminating bound the way
    // recogn.c's tighter dist<=1-only version is, so a wrong FALSE here
    // is tolerable in a way it would not be in recogn.c.
    if ((2 == TotalNonPawnCount(pos, uColor)) &&
        (1 == uColorBishops) &&
        (1 == TotalNonPawnCount(pos, xColor)) &&
        (0 == FastCountBits(pos->bbPawns[xColor])) &&
        (FastCountBits(pos->bbPawns[uColor]) > 0))
    {
        BITBOARD bbPawns = pos->bbPawns[uColor];
        COOR cPromote = ILLEGAL_COOR;
        ULONG uColorWhiteSquareBishopCount = WhiteSqBishopCount(pos, uColor);

        if (uColor == WHITE)
        {
            if (!(bbPawns & ~BBFILE[A]) && (uColorWhiteSquareBishopCount == 0))
            {
                cPromote = A8;
            }
            else if (!(bbPawns & ~BBFILE[H]) && (uColorWhiteSquareBishopCount == 1))
            {
                cPromote = H8;
            }
        }
        else
        {
            if (!(bbPawns & ~BBFILE[A]) && (uColorWhiteSquareBishopCount == 1))
            {
                cPromote = A1;
            }
            else if (!(bbPawns & ~BBFILE[H]) && (uColorWhiteSquareBishopCount == 0))
            {
                cPromote = H1;
            }
        }
        if (IS_ON_BOARD(cPromote))
        {
            COOR cWeakKing = KingPosition(pos, xColor);
            int iTempo = (pos->uToMove == xColor) ? 1 : 0;
            if (((int)DISTANCE(cWeakKing, cPromote) - iTempo) < 1)
            {
                return(FALSE);
            }
        }
    }

    //
    // A pawn always gives some winning chances (it can always try to
    // queen with support) -- nothing below applies.
    //
    if (FastCountBits(pos->bbPawns[uColor]) > 0)
    {
        return(TRUE);
    }

    // uSide's knight count is read twice below (the lone-minor check
    // and the two-knights check); uSideBishops was already computed
    // above.
    uColorKnights = FastCountBits(pos->bbPieces[uColor][KNIGHT]);

    //
    // No pawns and the only piece besides the king is a single minor:
    // never enough material to force mate (K+N or K+B vs anything is
    // never a forced win on material alone).
    //
    if ((2 == TotalNonPawnCount(pos, uColor)) &&
        (1 == (uColorKnights + uColorBishops)))
    {
        return(FALSE);
    }

    //
    // No pawns and up exactly the exchange (one extra rook/queen,
    // balanced by one extra enemy minor elsewhere): not enough to
    // force a win either -- e.g. KRB vs KR can be held by the
    // defender with correct play.
    //
    iMajorDiff = (INT)(FastCountBits(pos->bbPieces[uColor][ROOK]) +
                       2 * FastCountBits(pos->bbPieces[uColor][QUEEN])) -
                 (INT)(FastCountBits(pos->bbPieces[xColor][ROOK]) +
                      2 * FastCountBits(pos->bbPieces[xColor][QUEEN]));
    if ((1 == iMajorDiff) || (-1 == iMajorDiff))
    {
        iMinorDiff = (INT)(FastCountBits(pos->bbPieces[xColor][KNIGHT]) +
                          FastCountBits(pos->bbPieces[xColor][BISHOP])) -
                     (INT)(uColorKnights + uColorBishops);
        if (iMajorDiff == iMinorDiff)
        {
            return(FALSE);
        }
    }

    //
    // No pawns, exactly two bare knights (no bishops/rooks/queens) for
    // uSide, and the enemy has nothing left at all: two knights can't
    // force mate against a bare king. Two bishops CAN (excluded here
    // by requiring BISHOP count == 0) and knight+bishop CAN too (also
    // excluded, since that has one bishop, not zero) -- both are
    // genuine, if sometimes technique-heavy, forced wins.
    //
    if ((2 == uColorKnights) &&
        (0 == uColorBishops) &&
        (0 == FastCountBits(pos->bbPieces[uColor][ROOK])) &&
        (0 == FastCountBits(pos->bbPieces[uColor][QUEEN])) &&
        (1 == TotalNonPawnCount(pos, xColor)) &&
        (0 == FastCountBits(pos->bbPawns[xColor])))
    {
        return(FALSE);
    }
    return(TRUE);
}


void
InitializeEval(void)
{
    ROOK_FULL_HALF_OPEN_BONUS[0][0] = ROOK_ON_FULL_OPEN;
    ROOK_FULL_HALF_OPEN_BONUS[0][1] = ROOK_ON_HALF_OPEN_WITH_ENEMY;
    ROOK_FULL_HALF_OPEN_BONUS[1][0] = ROOK_ON_HALF_OPEN_WITH_FRIEND;
    ROOK_FULL_HALF_OPEN_BONUS[1][1] = 0;
}


// 2026-09-17: DRAWISH_FACTS holds the three position-only inputs
// EvalLookForDrawishSituations needs (_SideHasWinningChances for
// both sides, and the BOOC opposite-bishop check) -- none of these
// depend on the score at all, only on pos, which doesn't change
// between Eval()'s two call sites (the regular-lazy pre-exit check
// and the end of full eval). A node that attempts the lazy exit and
// then falls through to full eval anyway used to pay for
// _SideHasWinningChances (two calls) and the BOOC check twice, once
// per site, for identical answers both times -- only the score-vs-
// drawscore/50-move comparisons genuinely need to be re-run per call
// site, since the score itself legitimately differs between the
// early lazy-preview value and the final full-eval value.
// _EnsureDrawishFactsComputed is a cheap (single-branch) fetch-or-
// compute -- called at both sites so either call order (lazy-then-
// full, or full alone when the lazy attempt is skipped entirely for
// bare-king/low-material positions) computes the facts exactly once.
typedef struct _DRAWISH_FACTS
{
    FLAG fComputed;
    FLAG fSideToMoveHasWinningChances;
    FLAG fOpponentHasWinningChances;
    FLAG fBOOC;
} DRAWISH_FACTS;

static void
_EnsureDrawishFactsComputed(IN POSITION *pos, IN ULONG uColor,
                            IN OUT DRAWISH_FACTS *pFacts)
{
    if (pFacts->fComputed)
    {
        return;
    }
    pFacts->fSideToMoveHasWinningChances = SideHasWinningChances(pos, uColor);
    pFacts->fOpponentHasWinningChances =
        SideHasWinningChances(pos, FLIP(uColor));
    pFacts->fBOOC = (TotalNonPawnCount(pos, WHITE) == 2) &&
        (TotalNonPawnCount(pos, BLACK) == 2) &&
        (FastCountBits(pos->bbPieces[WHITE][BISHOP]) == 1) &&
        (FastCountBits(pos->bbPieces[BLACK][BISHOP]) == 1) &&
        (WhiteSqBishopCount(pos, WHITE) != WhiteSqBishopCount(pos, BLACK));
    pFacts->fComputed = TRUE;
}


static void
EvalLookForDrawishSituations(POSITION *pos,
                             SCORE *piScoreForSideToMove,
                             IN DRAWISH_FACTS *pFacts)
{
    ULONG uColor = pos->uToMove;

    ASSERT(pFacts->fComputed);

    // If the side who's ahead by raw material/positional score can't
    // actually force a win with what it has left on the board (see
    // _SideHasWinningChances), squash the score hard towards draw --
    // same idiom as the 50-move dampening just below (and the same
    // signed-arithmetic care: g_iDrawScore is currently always 0, but
    // write this relative to it rather than assuming that, matching
    // the 50-move code's own convention). /16 (not a full collapse to
    // drawscore) deliberately mirrors Crafty's EvaluateDraws -- e.g.
    // KRB vs KR is still theoretically losable by the run-of-the-mill
    // defender with the checks _SideHasWinningChances gates on, so
    // some residual signal survives.
    if ((*piScoreForSideToMove > g_iDrawScore[uColor]) &&
        (FALSE == pFacts->fSideToMoveHasWinningChances))
    {
        *piScoreForSideToMove = g_iDrawScore[uColor] +
            ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 16);
    }
    else if ((*piScoreForSideToMove < g_iDrawScore[uColor]) &&
             (FALSE == pFacts->fOpponentHasWinningChances))
    {
        *piScoreForSideToMove = g_iDrawScore[uColor] +
            ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 16);
    }

    // If this is a BOOC endgame, push towards draw score too.
    if (pFacts->fBOOC)
    {
        *piScoreForSideToMove = g_iDrawScore[uColor] +
            ((*piScoreForSideToMove - g_iDrawScore[uColor]) / 4);
    }

    // Drive the score towards draw as we approach a 50 move w/o
    // progress draw.
    if (pos->uFifty > 84)
    {
        ULONG uDrawDist = 101 - pos->uFifty;
        ASSERT(uDrawDist > 0);
        // uDrawDist is ULONG -- multiplying a negative SCORE by it
        // directly promotes the SCORE to unsigned first (usual
        // arithmetic conversions, same rank), wrapping a negative
        // *piScoreForSideToMove into a huge positive garbage value
        // instead of scaling it down. Cast uDrawDist to SCORE so the
        // multiply happens in signed arithmetic; its range (1-16) is
        // always representable.
        *piScoreForSideToMove = g_iDrawScore[uColor] +
            (*piScoreForSideToMove * (SCORE)uDrawDist / 16);
    }
}


#ifdef DUMP_RESIDUAL_SAMPLES
//
// Histogram-based percentile capture for residual (bucketed by OWN
// army scaler) and king safety (bucketed by ATTACKER's army scaler) --
// see the two call sites inside Eval() below. Deliberately a histogram
// (same idea as CALIBRATE_POSITIONAL's g_CalibrateHist), not a raw
// per-sample Trace: a raw dump against the 30k-position calibration
// pool would run into the billions of lines (a 200-position sample
// alone already produced 8.76M), while this stays a fixed, tiny amount
// of memory regardless of sample count and prints one summary via
// `calibrate residual`.
//
#define RESID_HIST_BUCKETS 8
#define RESID_HIST_BINS    90
#define RESID_HIST_BIN_WIDTH 20
#define RESID_HIST_MIN     (-900)

static UINT64 g_ResidualHist[RESID_HIST_BUCKETS][RESID_HIST_BINS];
static UINT64 g_SuperLazyResidualHist[RESID_HIST_BUCKETS][RESID_HIST_BINS];
static UINT64 g_KingSafetyHist[RESID_HIST_BUCKETS][RESID_HIST_BINS];
static INT g_ResidualMin[RESID_HIST_BUCKETS];
static INT g_ResidualMax[RESID_HIST_BUCKETS];
static INT g_SuperLazyResidualMin[RESID_HIST_BUCKETS];
static INT g_SuperLazyResidualMax[RESID_HIST_BUCKETS];
static INT g_KingSafetyMin[RESID_HIST_BUCKETS];
static INT g_KingSafetyMax[RESID_HIST_BUCKETS];
static FLAG g_fResidHistInit = FALSE;
static ULONG g_uResidualOutliersPrinted = 0;
static ULONG g_uKingSafetyOutliersPrinted = 0;

static void
_ResidHistInitIfNeeded(void)
{
    ULONG b;
    if (TRUE == g_fResidHistInit) return;
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        g_ResidualMin[b] = 999999;
        g_ResidualMax[b] = -999999;
        g_SuperLazyResidualMin[b] = 999999;
        g_SuperLazyResidualMax[b] = -999999;
        g_KingSafetyMin[b] = 999999;
        g_KingSafetyMax[b] = -999999;
    }
    g_fResidHistInit = TRUE;
}

static void
_RecordResidualSample(ULONG uOwnArmyBucket, INT iValue)
{
    INT idx;
    _ResidHistInitIfNeeded();
    idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH;
    if (idx < 0) idx = 0;
    if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1;
    g_ResidualHist[uOwnArmyBucket][idx]++;
    if (iValue < g_ResidualMin[uOwnArmyBucket]) g_ResidualMin[uOwnArmyBucket] = iValue;
    if (iValue > g_ResidualMax[uOwnArmyBucket]) g_ResidualMax[uOwnArmyBucket] = iValue;
}

static void
_RecordSuperLazyResidualSample(ULONG uOwnArmyBucket, INT iValue)
{
    INT idx;
    _ResidHistInitIfNeeded();
    idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH;
    if (idx < 0) idx = 0;
    if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1;
    g_SuperLazyResidualHist[uOwnArmyBucket][idx]++;
    if (iValue < g_SuperLazyResidualMin[uOwnArmyBucket]) g_SuperLazyResidualMin[uOwnArmyBucket] = iValue;
    if (iValue > g_SuperLazyResidualMax[uOwnArmyBucket]) g_SuperLazyResidualMax[uOwnArmyBucket] = iValue;
}

static void
_RecordKingSafetySample(ULONG uAttackerArmyBucket, INT iValue)
{
    INT idx;
    _ResidHistInitIfNeeded();
    idx = (iValue - RESID_HIST_MIN) / RESID_HIST_BIN_WIDTH;
    if (idx < 0) idx = 0;
    if (idx >= RESID_HIST_BINS) idx = RESID_HIST_BINS - 1;
    g_KingSafetyHist[uAttackerArmyBucket][idx]++;
    if (iValue < g_KingSafetyMin[uAttackerArmyBucket]) g_KingSafetyMin[uAttackerArmyBucket] = iValue;
    if (iValue > g_KingSafetyMax[uAttackerArmyBucket]) g_KingSafetyMax[uAttackerArmyBucket] = iValue;
}

static INT
_HistPercentile(UINT64 *puHist, UINT64 uTotal, double dP)
{
    UINT64 uTarget = (UINT64)(dP * (double)uTotal);
    UINT64 uRunning = 0;
    ULONG i;
    for (i = 0; i < RESID_HIST_BINS; i++)
    {
        uRunning += puHist[i];
        if (uRunning >= uTarget)
        {
            return RESID_HIST_MIN + (INT)(i * RESID_HIST_BIN_WIDTH) +
                (RESID_HIST_BIN_WIDTH / 2);
        }
    }
    return RESID_HIST_MIN + (RESID_HIST_BINS * RESID_HIST_BIN_WIDTH);
}

static void
_PersistRawHistogramsToFile(void)
/**

Routine description:

    2026-09-17: write every raw bin of all three histograms to a fixed
    scratch file, so any future percentile (not just the ones
    DumpResidualAndKingSafetyHistograms happens to print) can be read
    off after the fact -- no need to re-run the 30k pool just to try a
    different percentile choice. Plain text, one line per (histogram,
    bucket): the bucket's min, max, then all RESID_HIST_BINS raw counts
    space-separated. A future script can reconstruct any percentile via
    the same cumulative-sum logic _HistPercentile uses.

Parameters:

    void

Return value:

    void

**/
{
    FILE *f;
    ULONG b, i;

    f = fopen("/var/tmp/typhoon/residual_raw_histograms.txt", "w");
    if (NULL == f)
    {
        Trace("_PersistRawHistogramsToFile: could not open output file.\n");
        return;
    }
    fprintf(f, "# RESID_HIST_BINS=%d RESID_HIST_BIN_WIDTH=%d RESID_HIST_MIN=%d\n",
            RESID_HIST_BINS, RESID_HIST_BIN_WIDTH, RESID_HIST_MIN);
    fprintf(f, "# format: <histogram> <bucket> <min> <max> <bin0> <bin1> ... <binN-1>\n");
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        fprintf(f, "residual %u %d %d", b, g_ResidualMin[b], g_ResidualMax[b]);
        for (i = 0; i < RESID_HIST_BINS; i++)
        {
            fprintf(f, " %llu", (unsigned long long)g_ResidualHist[b][i]);
        }
        fprintf(f, "\n");
    }
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        fprintf(f, "sl_residual %u %d %d", b, g_SuperLazyResidualMin[b],
                g_SuperLazyResidualMax[b]);
        for (i = 0; i < RESID_HIST_BINS; i++)
        {
            fprintf(f, " %llu", (unsigned long long)g_SuperLazyResidualHist[b][i]);
        }
        fprintf(f, "\n");
    }
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        fprintf(f, "king %u %d %d", b, g_KingSafetyMin[b], g_KingSafetyMax[b]);
        for (i = 0; i < RESID_HIST_BINS; i++)
        {
            fprintf(f, " %llu", (unsigned long long)g_KingSafetyHist[b][i]);
        }
        fprintf(f, "\n");
    }
    fclose(f);
    Trace("Raw histograms written to /var/tmp/typhoon/residual_raw_histograms.txt\n");
}

void
DumpResidualAndKingSafetyHistograms(void)
{
    ULONG b, i;
    UINT64 uTotal;

    _PersistRawHistogramsToFile();

#define TRACE_HIST_ROW(hist, min, max)                                 \
    Trace("  bucket %u (scaler %u-%u): n=%llu min=%d p1=%d p2=%d "     \
          "p5=%d p10=%d p50=%d p90=%d p95=%d p98=%d p99=%d max=%d\n",  \
          b, b * 4, b * 4 + 3, (unsigned long long)uTotal, (min),      \
          _HistPercentile((hist), uTotal, 0.01),                       \
          _HistPercentile((hist), uTotal, 0.02),                       \
          _HistPercentile((hist), uTotal, 0.05),                       \
          _HistPercentile((hist), uTotal, 0.10),                       \
          _HistPercentile((hist), uTotal, 0.50),                       \
          _HistPercentile((hist), uTotal, 0.90),                       \
          _HistPercentile((hist), uTotal, 0.95),                       \
          _HistPercentile((hist), uTotal, 0.98),                       \
          _HistPercentile((hist), uTotal, 0.99),                       \
          (max))

    Trace("Residual by OWN army-scaler bucket:\n");
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        uTotal = 0;
        for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_ResidualHist[b][i];
        if (0 == uTotal)
        {
            Trace("  bucket %u: no samples\n", b);
            continue;
        }
        TRACE_HIST_ROW(g_ResidualHist[b], g_ResidualMin[b], g_ResidualMax[b]);
    }

    Trace("Super-lazy-scoped residual (material baseline, includes "
          "pawns/passers/bad-trade/bishop-pairs) by OWN army-scaler "
          "bucket:\n");
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        uTotal = 0;
        for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_SuperLazyResidualHist[b][i];
        if (0 == uTotal)
        {
            Trace("  bucket %u: no samples\n", b);
            continue;
        }
        TRACE_HIST_ROW(g_SuperLazyResidualHist[b], g_SuperLazyResidualMin[b],
                       g_SuperLazyResidualMax[b]);
    }

    Trace("King safety by ATTACKER army-scaler bucket:\n");
    for (b = 0; b < RESID_HIST_BUCKETS; b++)
    {
        uTotal = 0;
        for (i = 0; i < RESID_HIST_BINS; i++) uTotal += g_KingSafetyHist[b][i];
        if (0 == uTotal)
        {
            Trace("  bucket %u: no samples\n", b);
            continue;
        }
        TRACE_HIST_ROW(g_KingSafetyHist[b], g_KingSafetyMin[b],
                       g_KingSafetyMax[b]);
    }
#undef TRACE_HIST_ROW
}
#endif


SCORE
Eval(IN SEARCHER_THREAD_CONTEXT *ctx,
     IN SCORE iAlpha,
     IN SCORE iBeta,
     OUT SCORE (*piPositional)[2])
/**

Routine description:

Parameters:

    SEARCHER_THREAD_CONTEXT *ctx,
    SCORE iAlpha,
    SCORE iBeta,
    SCORE (*piPositional)[2] : if non-NULL, filled in with an estimate
        of the non-material component of the score for each side,
        indexed by absolute color (WHITE/BLACK) -- exact if a full
        eval ran, a cheap estimate otherwise. On a lazy exit this is
        always >= 0 (an optimistic margin); on a full eval it can be
        negative (a side whose positional terms net worse than its
        raw material), floored at -FUTILITY_BASE_MARGIN_FULL/2 so it can
        only shrink a caller's margin so far. Callers must treat it
        as an estimate either way; it's only ever used to size a
        pruning margin, never as a hard fact.

Return value:

    SCORE

**/
{
    POSITION *pos = &(ctx->sPosition);
    ULONG uColor = pos->uToMove;
    ULONG xColor = FLIP(uColor);
    SCORE iScoreForSideToMove;
    SCORE iAlphaMargin, iBetaMargin;
    PAWN_HASH_ENTRY *pHash;
    COOR c;
    ULONG u;
    BITBOARD bb;
    FLAG fDeferred;
    // Computed at most once per Eval() call, on first need, by
    // whichever of the two EvalLookForDrawishSituations call sites
    // runs first -- see DRAWISH_FACTS's comment above.
    DRAWISH_FACTS sDrawishFacts = {0};
#ifdef EVAL_TIME
    UINT64 uTimer = SystemReadTimeStampCounter();
#endif
#ifdef CALIBRATE_POSITIONAL
    g_uCalibrateEvalCalls++;
#endif
#ifdef CALIBRATE_MARGIN_SAFETY
    // Set when a real exit would have been taken; the rest of Eval()
    // still runs (for measurement), but the saved values get restored
    // just before returning so real search behavior is bit-for-bit
    // unaffected -- see the swing recorded near `end:` below.
    FLAG fWouldHaveExited = FALSE;
    SCORE iSavedLazyScore = 0;
    SCORE iSavedLazyPositional = 0;
    // 2026-09-17: iPositional is no longer flat/symmetric across colors
    // (p50-based, keyed by each side's own army bucket) -- iSavedLazy-
    // Positional above stays the margin-safety accounting value (still
    // symmetric, unrelated to iPositional), these two are what actually
    // gets restored into (*piPositional)[WHITE]/[BLACK] below.
    SCORE iSavedLazyPositionalWhite = 0;
    SCORE iSavedLazyPositionalBlack = 0;
    // Same idea, kept separate from the pair above: the super-lazy
    // exit (added 2026-09-07) is a much cheaper, much-larger-gap check
    // than the regular lazy exit and was never hooked into this
    // harness -- see RecordSuperLazyMarginSafetySwing below.
    FLAG fWouldHaveExitedSuperLazy = FALSE;
    SCORE iSavedSuperLazyScore = 0;
    SCORE iSavedSuperLazyMarginUsed = 0;
#endif
    ASSERT(IS_VALID_SCORE(iAlpha));
    ASSERT(IS_VALID_SCORE(iBeta));
    ASSERT(iAlpha < iBeta);
    ASSERT((pos->iMaterialBalance[WHITE] * -1) ==
           pos->iMaterialBalance[BLACK]);

#ifdef EVAL_TIME
    UINT64 u64MaterialSetupTimer = SystemReadTimeStampCounter();
#endif
#ifdef EVAL_DUMP
    EvalTraceClear();
#endif

    // NNUE short-circuit (docs/NNUE.md's rollout plan: keep both
    // evaluators coexisting behind a toggle, full bypass not partial
    // mixing). ctx->sNnueAccum is assumed correct here -- maintained
    // incrementally by every MakeMove/UnmakeMove since the last fresh
    // NnueAccumRecompute (root.c's ReInitializeSearcherContext, run
    // on every new root position). piPositional's contract ("always
    // >= 0 on anything but a full eval") is satisfied with a neutral
    // 0 -- none of the lazy/super-lazy margin-sizing machinery below
    // has been recalibrated against NNUE's score distribution yet
    // (a separate, not-yet-done project per NNUE.md), so this is
    // intentionally the least-specific answer that's still safe, not
    // an attempt to approximate what a real positional estimate would
    // say.
    if ((TRUE == g_fUseNnueEval) && (TRUE == g_fNnueWeightsLoaded))
    {
        SCORE iNnueScore = NnueForward(ctx);
        if (NULL != piPositional)
        {
            (*piPositional)[WHITE] = 0;
            (*piPositional)[BLACK] = 0;
        }
        return iNnueScore;
    }

    // Initialize army scalers here (moved ahead of the super-lazy exit
    // point below, 2026-09-08 -- their only inputs, uNonPawnMaterial,
    // are already available this early, and the super-lazy margin
    // table needs a material bucket before it can run). We skip lazy
    // eval if we're too late into an endgame.
    pos->uArmyScaler[BLACK] = pos->uNonPawnMaterial[BLACK] - VALUE_KING;
    pos->uArmyScaler[WHITE] = pos->uNonPawnMaterial[WHITE] - VALUE_KING;
    pos->uArmyScaler[BLACK] /= VALUE_PAWN;
    pos->uArmyScaler[WHITE] /= VALUE_PAWN;
    ASSERT(!(pos->uArmyScaler[BLACK] & 0x80000000));
    ASSERT(!(pos->uArmyScaler[WHITE] & 0x80000000));
    pos->uArmyScaler[BLACK] = MINU(31, pos->uArmyScaler[BLACK]);
    pos->uArmyScaler[WHITE] = MINU(31, pos->uArmyScaler[WHITE]);
    ASSERT(pos->uArmyScaler[BLACK] >= 0);
    ASSERT(pos->uArmyScaler[BLACK] <= 31);
    ASSERT(pos->uArmyScaler[WHITE] >= 0);
    ASSERT(pos->uArmyScaler[WHITE] <= 31);
#ifdef EVAL_TIME
    ctx->sCounters.tree.u64CyclesEvalMaterialSetup +=
        (SystemReadTimeStampCounter() - u64MaterialSetupTimer);
#endif

#ifdef DUMP_RESIDUAL_SAMPLES
    // Super-lazy's OWN baseline -- material only, before _EvalPawns
    // even runs. Separate from iResidualBaselineWhite/Black below
    // (captured after bishop pairs, i.e. regular-lazy's baseline):
    // that measurement deliberately excludes pawns/passers/bad-trade/
    // bishop-pairs, which is correct for regular lazy (which already
    // has all of that by the time it asks) but wrong for super-lazy,
    // which has NONE of it yet. This is what a super-lazy-scoped
    // residual needs to be measured against instead.
    SCORE iSuperLazyResidualBaselineWhite = pos->iScore[WHITE];
    SCORE iSuperLazyResidualBaselineBlack = pos->iScore[BLACK];
#endif

    // 2026-09-16: shared "too dangerous to shortcut" gate for both lazy
    // tiers -- exactly the condition search.c's own passer-race code
    // (_EvalPasserRacesAgainstLoneKings' caller) uses to decide whether
    // the volatile won-passer-race verdict can fire: one side down to
    // literally just a king (TotalNonPawnCount counts the king itself
    // as 1, so ==1 means no other non-pawn material at all). Regular
    // lazy already had a blunter, broader guard for this material
    // region (LAZY_EVAL_MIN_MATERIAL, a combined-army-scaler band) --
    // but that band doesn't actually imply either side is bare-king
    // (e.g. a heavy attacker vs. a bare king can have a large combined
    // scaler despite one side having zero other material), so it
    // wasn't sufficient on its own. Super-lazy had no such guard at
    // all. Folding EvalLookForDrawishSituations into both tiers (above/
    // below) closes the "insufficient winning chances"/BOOC/50-move
    // gap; this closes the remaining one -- the passer-race verdict
    // needs pHash->bbPasserLocations, which isn't available yet at
    // super-lazy's point in Eval() (it runs before _EvalPawns), so
    // that correction can't cheaply be folded in the same way and the
    // honest answer here is to just not shortcut in this regime.
    FLAG fBareKingEitherSide = (1 == TotalNonPawnCount(pos, WHITE)) ||
                               (1 == TotalNonPawnCount(pos, BLACK));

    // Super-lazy exit point.
#ifdef LAZY_EVAL
    // Combined-army bucket, still needed by the bucket-0 exclusion
    // below (a structural exclusion of pawn-dominated near-bare-army
    // positions, unrelated to the margin construction itself).
    ULONG uSuperLazyMatBucket = MINU(
        7, (pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK]) / 8);

    // 2026-09-16: exclude material bucket 0 (combined non-pawn army
    // scaler 0-7) from super-lazy entirely -- CALIBRATE_MARGIN_SAFETY
    // against 30k stratified positions found a 6.8% exceeded rate
    // there even after the bare-king exclusion above and the
    // EvalLookForDrawishSituations fix, traced by hand to real,
    // externally-corroborated (cross-checked against Crafty's own eval
    // breakdown on the same position, within 7%) swings of 650-750+
    // centipawns from knight-vs-bishop-with-several-pawns-per-side
    // endgames. Root cause: this bucket is defined purely by non-pawn
    // material, so it says nothing about how many pawns are on the
    // board, and super-lazy runs before _EvalPawns entirely -- meaning
    // it's not just imprecise about pawn structure here, it's totally
    // blind to it, in exactly the material regime where pawns (passed-
    // pawn recognition, king-supports-own-passer, _ReEvalPassers) can
    // be nearly the entire evaluation. Not a bug to fix with a bigger
    // constant -- a structural mismatch between what this bucket
    // measures (piece count) and what actually drives the score
    // (pawn count) in this exact material range. Bucket 1+ (scaler
    // >=8) doesn't have this problem to nearly the same degree since
    // there's enough non-pawn material for pieces to matter alongside
    // pawns, not be dwarfed by them.
    if ((FALSE == fBareKingEitherSide) && (uSuperLazyMatBucket > 0))
    {
#ifdef EVAL_TIME
        UINT64 uSuperLazyTimer = SystemReadTimeStampCounter();
#endif
        iScoreForSideToMove = pos->iMaterialBalance[uColor];
        ASSERT(IS_VALID_SCORE(iScoreForSideToMove));

        // We have a super-rough eval -- material only at this point.
        // Compute two margins to check whether things look so good or
        // bad that we need not refine our eval because we are sure to
        // FH/FL anyway.
        ULONG uSuperLazyMyBucket = MINU(7, pos->uArmyScaler[uColor] / 4);
        ULONG uSuperLazyOppBucket = MINU(7, pos->uArmyScaler[xColor] / 4);
        SCORE iSuperLazySelfPessEnemyOptMargin = MAX0(
            (iKingP98ByAttackerArmy[uSuperLazyMyBucket] -
             iKingP2ByAttackerArmy[uSuperLazyOppBucket]) +
            (iSuperLazyResidualOptimisticByOwnArmy[uSuperLazyOppBucket] -
             iSuperLazyResidualPessimisticByOwnArmy[uSuperLazyMyBucket]));
        SCORE iSuperLazySelfOptEnemyPessMargin = MAX0(
            (iKingP98ByAttackerArmy[uSuperLazyOppBucket] -
             iKingP2ByAttackerArmy[uSuperLazyMyBucket]) +
            (iSuperLazyResidualOptimisticByOwnArmy[uSuperLazyMyBucket] -
             iSuperLazyResidualPessimisticByOwnArmy[uSuperLazyOppBucket]));

        if (iScoreForSideToMove + iSuperLazySelfOptEnemyPessMargin < iAlpha)
        {
            ASSERT(iScoreForSideToMove < iAlpha);
#ifdef CALIBRATE_MARGIN_SAFETY
            iSavedSuperLazyMarginUsed = iSuperLazySelfOptEnemyPessMargin;
#endif
            INC(ctx->sCounters.tree.u64SuperLazyEvals);
            g_u64SuperLazyEvalsByBucket[_MaterialBucket(pos)]++;
            if (NULL != piPositional)
            {
                // 2026-09-17: no longer flat 0 -- same p50-based typical-
                // value estimate as regular lazy, using the super-lazy-
                // scoped residual table (material-only baseline). See
                // iKingP50ByAttackerArmyOnly/iSuperLazyResidualP50By-
                // OwnArmy (file-scope, above).
                ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4);
                ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4);
                (*piPositional)[WHITE] =
                    iKingP50ByAttackerArmy[uBlackBucket] +
                    iSuperLazyResidualP50ByOwnArmy[uWhiteBucket];
                (*piPositional)[BLACK] =
                    iKingP50ByAttackerArmy[uWhiteBucket] +
                    iSuperLazyResidualP50ByOwnArmy[uBlackBucket];
                ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY;
            }
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalSuperLazy +=
                (SystemReadTimeStampCounter() - uSuperLazyTimer);
#endif
#ifdef CALIBRATE_MARGIN_SAFETY
            // Don't exit yet -- let the real full eval run below so we
            // can measure the true swing against SUPER_LAZY_MARGIN,
            // then restore this exact (zeroed) piPositional right
            // before `end:` so the caller sees what a normal build
            // would have returned.
            fWouldHaveExitedSuperLazy = TRUE;
            iSavedSuperLazyScore = iScoreForSideToMove;
#else
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalPreLazy +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesSuperLazyExit +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesInEval +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
            goto end;
#endif
        }

        if (iScoreForSideToMove - iSuperLazySelfPessEnemyOptMargin > iBeta)
        {
            ASSERT(iScoreForSideToMove > iBeta);
#ifdef CALIBRATE_MARGIN_SAFETY
            iSavedSuperLazyMarginUsed = iSuperLazySelfPessEnemyOptMargin;
#endif
            INC(ctx->sCounters.tree.u64SuperLazyEvals);
            g_u64SuperLazyEvalsByBucket[_MaterialBucket(pos)]++;
            if (NULL != piPositional)
            {
                // See the analogous alpha-side branch above -- same p50
                // typical-value estimate.
                ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4);
                ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4);
                (*piPositional)[WHITE] =
                    iKingP50ByAttackerArmy[uBlackBucket] +
                    iSuperLazyResidualP50ByOwnArmy[uWhiteBucket];
                (*piPositional)[BLACK] =
                    iKingP50ByAttackerArmy[uWhiteBucket] +
                    iSuperLazyResidualP50ByOwnArmy[uBlackBucket];
                ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY;
            }
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalSuperLazy +=
                (SystemReadTimeStampCounter() - uSuperLazyTimer);
#endif
#ifdef CALIBRATE_MARGIN_SAFETY
            fWouldHaveExitedSuperLazy = TRUE;
            iSavedSuperLazyScore = iScoreForSideToMove;
#else
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalPreLazy +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesSuperLazyExit +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesInEval +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
            goto end;
#endif
        }
#ifdef EVAL_TIME
        ctx->sCounters.tree.u64CyclesEvalSuperLazy +=
            (SystemReadTimeStampCounter() - uSuperLazyTimer);
#endif
    }
#endif

    // If we get here, we did not take the super lazy exit.  This is
    // either a lazy exit node or a full eval node.

    // Pawn eval.  Note: if fDeferred comes back as TRUE then we have
    // neither cleared nor initialized the attack tables.  This is
    // because we hope that we can still get a lazy eval exit here and
    // save some time.  BEFORE ANY CODE BELOW TOUCHES THE ATTACK
    // TABLES IT NEEDS TO CLEAR/POPULATE THEM THOUGH!!!
#ifdef EVAL_TIME
    UINT64 u64PawnTimer = SystemReadTimeStampCounter();
    pHash = EvalPawns(ctx, &fDeferred);
    {
        UINT64 u64Elapsed = SystemReadTimeStampCounter() - u64PawnTimer;
        ctx->sCounters.tree.u64CyclesEvalPawns += u64Elapsed;
        if (fDeferred)
        {
            ctx->sCounters.tree.u64CyclesEvalPawnsHit += u64Elapsed;
            ctx->sCounters.tree.u64CountEvalPawnsHit++;
        }
        else
        {
            ctx->sCounters.tree.u64CyclesEvalPawnsMiss += u64Elapsed;
            ctx->sCounters.tree.u64CountEvalPawnsMiss++;
        }
    }
#else
    pHash = EvalPawns(ctx, &fDeferred);
#endif
    ASSERT(NULL != pHash);
    ASSERT(IS_VALID_FLAG(fDeferred));
    pos->iScore[uColor] =
        (PawnMaterial(pos, uColor) + pos->uNonPawnMaterial[uColor] + pHash->iScore[uColor]);
    pos->iScore[xColor] =
        (PawnMaterial(pos, xColor) + pos->uNonPawnMaterial[xColor] + pHash->iScore[xColor]);
    ASSERT(IS_VALID_SCORE(pos->iScore[WHITE] - pos->iScore[BLACK]));
#ifdef EVAL_DUMP
    Trace("After pawns + material:\n%d\t\t%d\t\t(%d for %s)\n",
          pos->iScore[WHITE], pos->iScore[BLACK],
          (pos->iScore[uColor] - pos->iScore[xColor]),
          COLOR_NAME(uColor)
    );
#endif

    // Look for won passers races.  Note: This code cannot trust the
    // state of the attack tables yet!
#ifdef EVAL_TIME
    UINT64 u64PasserBadtradeBishopTimer = SystemReadTimeStampCounter();
#endif
    if (fBareKingEitherSide)
    {
        //
        // Pure king-and-pawns on BOTH sides: try the new,
        // exhaustively-verified shared logic first (see
        // _EvalUnstoppablePasser's header comment) -- it's trustworthy
        // whenever it has something to say. But it only ever fires for
        // the true-lone-king sub-case and stays silent (FALSE) for the
        // "both sides still have pawns" sub-case, which the old,
        // broader-but-dodgier heuristic used to cover -- fall back to
        // that old heuristic rather than simply losing that coverage.
        // Anything broader than pure KPvKP (one bare side, but the
        // OTHER side still has real pieces -- e.g. K+R+P vs K) always
        // uses the old heuristic unchanged; that shape was never
        // covered by this session's KPvKP investigation.
        //
        if ((1 == TotalNonPawnCount(pos, WHITE)) &&
            (1 == TotalNonPawnCount(pos, BLACK)))
        {
            if (FALSE == _EvalUnstoppablePasser(pos))
            {
                (void)_EvalPasserRacesAgainstLoneKings(ctx, pHash);
            }
        }
        else
        {
            (void)_EvalPasserRacesAgainstLoneKings(ctx, pHash);
        }
#ifdef EVAL_DUMP
        Trace("After passer races:\n%d\t\t%d\t\t(%d for %s)\n",
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Bad trade code.  Note: this code cannot trust the state of the
    // attack tables...
    if (pos->uNonPawnMaterial[WHITE] != pos->uNonPawnMaterial[BLACK])
    {
        _EvalBadTrades(pos);
#ifdef EVAL_DUMP
        Trace("After bad trades:\n%d\t\t%d\t\t(%d for %s)\n",
              pos->iScore[WHITE],
              pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Bishop pairs.  Again... Note: this code cannot trust the state
    // of the attack tables.
    _EvalBishopPairs(pos);
#ifdef EVAL_DUMP
    Trace("After bishop pair bonus:\n%d\t\t%d\t\t(%d for %s)\n",
          pos->iScore[WHITE],
          pos->iScore[BLACK],
          (pos->iScore[uColor] - pos->iScore[xColor]),
          COLOR_NAME(uColor)
    );
#endif
#ifdef EVAL_TIME
    ctx->sCounters.tree.u64CyclesEvalPasserBadtradeBishop +=
        (SystemReadTimeStampCounter() - u64PasserBadtradeBishopTimer);
#endif

#ifdef DUMP_RESIDUAL_SAMPLES
    // Snapshot right here: material + pawns/passers + bad-trade +
    // bishop pairs, before king safety or mobility/misc positional
    // terms run. Subtracting this (the same baseline regular lazy
    // itself reads its score from) plus the real per-side king score
    // (ctx->sPlyInfo[ctx->uPly].iKingScore[color], stored once
    // _EvalKing runs for that side) from the final full-eval score
    // isolates exactly what iResidualP98 is trying to estimate:
    // mobility + trapped pieces + everything else, with passers
    // already excluded. See the dump site below, near "Almost done".
    SCORE iResidualBaselineWhite = pos->iScore[WHITE];
    SCORE iResidualBaselineBlack = pos->iScore[BLACK];
#endif

#ifdef LAZY_EVAL
    // Below LAZY_EVAL_MIN_MATERIAL combined army scaler, skip lazy eval
    // entirely (see its chess.h comment) -- measured directly via
    // CALIBRATE_MARGIN_SAFETY, the regular lazy exit's real swing
    // exceeded its own assumed margin 20.6% of the time in near-bare-
    // king endgames, far above the ~0.01-0.36% rate everywhere else.
    // fBareKingEitherSide (set above, before the super-lazy exit point)
    // is a separate, more precise guard for the specific passer-race
    // mechanism -- kept in addition to this band, not instead of it,
    // since a heavy attacker vs. a bare king can still clear this
    // combined-scaler threshold despite one side being bare-king.
    if ((pos->uArmyScaler[WHITE] + pos->uArmyScaler[BLACK] >=
         LAZY_EVAL_MIN_MATERIAL) &&
        (FALSE == fBareKingEitherSide))
    {
#ifdef EVAL_TIME
        UINT64 uLazyDecisionTimer = SystemReadTimeStampCounter();
#endif
        //
        // Compute an estimate of the score for the side to move based on the
        // eval terms we have already considered:
        //
        //     1. Material balance
        //     2. Pawn structure bonuses/penalties (incl passers/candidates)
        //     3. Passer races are detected already
        //     4. "Bad trade" code has already run
        //     5. Bishop pairs
        //
        iScoreForSideToMove = (pos->iScore[uColor] - pos->iScore[xColor]);
        ASSERT(IS_VALID_SCORE(iScoreForSideToMove));

        // 2026-09-16: item 5 used to claim "we've already detected
        // unwinnable endgames" here, but nothing before this point
        // actually did -- EvalLookForDrawishSituations (insufficient-
        // winning-chances squash, BOOC, 50-move dampening) was only
        // ever called once, at the very end of the FULL eval path
        // (see its call site below), so a regular-lazy exit could
        // return a raw material-ahead score (e.g. "+300, bishop up")
        // in a position full eval would have squashed hard toward a
        // draw (BOOC: /4; no forcing material: /16) -- a large swing
        // with nothing to do with king safety or mobility. Call it
        // here too so regular lazy sees the same correction full eval
        // would apply. Cheap and safe to do this early: unlike
        // king safety/mobility, none of EvalLookForDrawishSituations'
        // three checks touch attack bitboards, only piece bitboards/
        // counts and pos->uFifty, all already valid by this point.
        // _EnsureDrawishFactsComputed is a no-op if the call site
        // below (full eval, if this node falls through to it) already
        // populated sDrawishFacts -- can't happen in this order since
        // this is the first potential call site, but written this way
        // so either call order is correct.
        TIMED_EVAL_CALL(ctx, u64CyclesEvalDrawish,
                        (_EnsureDrawishFactsComputed(pos, uColor, &sDrawishFacts),
                         EvalLookForDrawishSituations(pos, &iScoreForSideToMove,
                                                      &sDrawishFacts)));

        //
        // Eval has not considered several potentially large terms:
        //
        //     1. Piece positional components (such as mobility, trapped)
        //     2. King safety penalties (which can be large!)
        //     3. Other miscellaneous bonuses/penalties
        //
        // We build two "margins" to account for these components of the
        // score.
        //
        // 2026-09-17: no flat base margin, no floor -- matches super-
        // lazy's convention. margin_a'/margin_b' (built entirely by
        // EstimatePositionalScore below) stand alone. If CALIBRATE_
        // MARGIN_SAFETY turns up a real, non-trivial exceeded rate once
        // this is validated against the 30k pool, the fix is tightening
        // the percentile choice there (e.g. p95/p5 or p99/p1), not
        // resurrecting a flat backstop that would just override the
        // position-specific estimate again.
        iAlphaMargin = iBetaMargin = 0;
#ifdef CALIBRATE_POSITIONAL
        ctx->fCalibrateCandidate = FALSE;
        g_uCalibrateGateChecked++;
#endif
#ifdef CALIBRATE_POSITIONAL
        g_uCalibrateGateTrue++;
#endif
        //
        // Ok, we can't say for sure that we won't take a lazy exit
        // yet.  So do the expensive part of lazy eval estimation and
        // widen the margin further for king safety issues and passed
        // pawns.
        //
#ifdef CALIBRATE_POSITIONAL
        // This node is one where a real (uninstrumented) build would
        // actually call EstimatePositionalScore and consider a lazy
        // exit -- the population _RecordPositionalCalibration should
        // be sampling from, per _EvalKing's calls below.
        ctx->fCalibrateCandidate = TRUE;
#endif
        EstimatePositionalScore(ctx, pos, pHash, &iAlphaMargin, &iBetaMargin);

#ifdef CALIBRATE_BASE_MARGIN
        ULONG uBucket = _MaxKingDangerBucket(ctx, pos, pHash);
        ULONG uMatBucket = _MaterialBucket(pos);
        g_uBaseMarginExitAttempted[uMatBucket][uBucket]++;
        if ((iScoreForSideToMove + iAlphaMargin <= iAlpha) ||
            (iScoreForSideToMove - iBetaMargin >= iBeta))
        {
            g_uBaseMarginExitTaken[uMatBucket][uBucket]++;
        }
#endif

        // CALIBRATE_POSITIONAL builds never take the lazy exit here --
        // the whole point of a calibration run is to compute the cheap
        // defect-count estimate *and* let Eval() continue on to
        // _EvalKing's real computation on every node, so the two can be
        // logged and compared. See _RecordPositionalCalibration below
        // (called from _EvalKing) and DumpPositionalCalibration
        // (command.c's "calibrate dump").
#ifndef CALIBRATE_POSITIONAL
        if (iScoreForSideToMove + iAlphaMargin <= iAlpha)
        {
            INC(ctx->sCounters.tree.u64LazyEvals);
            g_u64LazyEvalsByBucket[_MaterialBucket(pos)]++;
            if (NULL != piPositional)
            {
                // 2026-09-17: no longer flat 0 -- a p50-based typical-
                // value estimate of this side's own missing positional
                // terms (king safety + residual), matching full-eval's
                // own iPositional convention (that side's own real
                // positional score, not a relative-to-opponent
                // quantity). See iKingP50ByAttackerArmyOnly/
                // iResidualP50ByOwnArmy (file-scope, above) for the
                // full percentile charts this was derived from.
                ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4);
                ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4);
                (*piPositional)[WHITE] =
                    iKingP50ByAttackerArmy[uBlackBucket] +
                    iResidualP50ByOwnArmy[uWhiteBucket];
                (*piPositional)[BLACK] =
                    iKingP50ByAttackerArmy[uWhiteBucket] +
                    iResidualP50ByOwnArmy[uBlackBucket];
                ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY;
            }
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalPreLazy +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
#ifdef CALIBRATE_MARGIN_SAFETY
            // Don't exit yet -- let the real full eval run below so we
            // can measure the true swing, then restore these values
            // right before `end:` so the caller sees exactly what a
            // normal build would have returned.
            fWouldHaveExited = TRUE;
            iSavedLazyScore = iScoreForSideToMove;
            iSavedLazyPositional = iAlphaMargin;
            iSavedLazyPositionalWhite =
                iKingP50ByAttackerArmyOnly[MINU(7, pos->uArmyScaler[BLACK] / 4)] +
                iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)];
            iSavedLazyPositionalBlack =
                iKingP50ByAttackerArmyOnly[MINU(7, pos->uArmyScaler[WHITE] / 4)] +
                iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)];
#else
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalLazyDecision +=
                (SystemReadTimeStampCounter() - uLazyDecisionTimer);
            ctx->sCounters.tree.u64CyclesLazyExit +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesInEval +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
            goto end;
#endif
        }
        else if (iScoreForSideToMove - iBetaMargin >= iBeta)
        {
            INC(ctx->sCounters.tree.u64LazyEvals);
            g_u64LazyEvalsByBucket[_MaterialBucket(pos)]++;
            if (NULL != piPositional)
            {
                // See the analogous fail-low branch above -- same p50
                // typical-value estimate, not a flat 0 or the margin
                // itself.
                ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4);
                ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4);
                (*piPositional)[WHITE] =
                    iKingP50ByAttackerArmy[uBlackBucket] +
                    iResidualP50ByOwnArmy[uWhiteBucket];
                (*piPositional)[BLACK] =
                    iKingP50ByAttackerArmy[uWhiteBucket] +
                    iResidualP50ByOwnArmy[uBlackBucket];
                ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY;
            }
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalPreLazy +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
#ifdef CALIBRATE_MARGIN_SAFETY
            fWouldHaveExited = TRUE;
            iSavedLazyScore = iScoreForSideToMove;
            iSavedLazyPositional = iBetaMargin;
            iSavedLazyPositionalWhite =
                iKingP50ByAttackerArmyOnly[MINU(7, pos->uArmyScaler[BLACK] / 4)] +
                iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[WHITE] / 4)];
            iSavedLazyPositionalBlack =
                iKingP50ByAttackerArmyOnly[MINU(7, pos->uArmyScaler[WHITE] / 4)] +
                iResidualP50ByOwnArmy[MINU(7, pos->uArmyScaler[BLACK] / 4)];
#else
#ifdef EVAL_TIME
            ctx->sCounters.tree.u64CyclesEvalLazyDecision +=
                (SystemReadTimeStampCounter() - uLazyDecisionTimer);
            ctx->sCounters.tree.u64CyclesLazyExit +=
                (SystemReadTimeStampCounter() - uTimer);
            ctx->sCounters.tree.u64CyclesInEval +=
                (SystemReadTimeStampCounter() - uTimer);
#endif
            goto end;
#endif
        }
#endif // !CALIBRATE_POSITIONAL
#ifdef EVAL_TIME
        ctx->sCounters.tree.u64CyclesEvalLazyDecision +=
            (SystemReadTimeStampCounter() - uLazyDecisionTimer);
#endif
    } // lazy eval
#endif

#ifdef EVAL_TIME
    ctx->sCounters.tree.u64CyclesEvalPreLazy +=
        (SystemReadTimeStampCounter() - uTimer);
#endif

    // If we get here we are doing a full eval.
    ctx->sPlyInfo[ctx->uPly].u64FullEvalSig = (pos->u64NonPawnSig ^ pos->u64PawnSig);

    // See if we have to clear/populate the pawn attack table.
    if (TRUE == fDeferred)
    {
        TIMED_EVAL_CALL(ctx, u64CyclesEvalAttackTablePop,
                        _PopulatePawnAttackBits(pos));
    }

    // Pre-compute some common terms used in per-piece evals:
    pos->uNumTrapped[BLACK] = pos->uNumTrapped[WHITE] = 0;
    pos->iReducedMaterialDownScaler[BLACK] =
        pos->iReducedMaterialDownScaler[WHITE] = 0;
    pos->uMinorsAtHome[BLACK] = pos->uMinorsAtHome[WHITE] = 0;

    //
    // Evaluate individual pieces.
    //

    // Precomputed once per color instead of rebuilt by every bishop/
    // rook/queen of that color (see MOBILITY_BITBOARD_REWRITE.md's
    // "squeeze it" follow-up). bbEnemyRQK/bbEnemyQK depend only on
    // static piece locations -- no ordering dependency, safe to build
    // right here before any piece loop runs. bbUnsafeForRook/
    // bbUnsafeForQueen are filled in below, at the loop boundary where
    // their inputs are guaranteed complete (both colors' knight+bishop
    // passes before rook; both colors' pawn/minor/rook passes before
    // queen) -- NOT incrementally mutated during a loop, which would
    // let one piece's own attack leak into its same-color sibling's
    // "unsafe" mask.
    BITBOARD bbEnemyRQK[2];
    BITBOARD bbEnemyQK[2];
    BITBOARD bbUnsafeForRook[2];
    BITBOARD bbUnsafeForQueen[2];

    bbEnemyQK[WHITE] = pos->bbPieces[WHITE][QUEEN] |
        COOR_TO_BB(pos->cKingSq[WHITE]);
    bbEnemyQK[BLACK] = pos->bbPieces[BLACK][QUEEN] |
        COOR_TO_BB(pos->cKingSq[BLACK]);
    bbEnemyRQK[WHITE] = bbEnemyQK[WHITE] | pos->bbPieces[WHITE][ROOK];
    bbEnemyRQK[BLACK] = bbEnemyQK[BLACK] | pos->bbPieces[BLACK][ROOK];

    // Knights.
    bb = pos->bbPieces[uColor][KNIGHT];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalKnight,
                         _EvalKnight(pos, c, pHash));
#ifdef EVAL_DUMP
        Trace("After our N at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Enemy knights.
    ASSERT(xColor != pos->uToMove);
    bb = pos->bbPieces[xColor][KNIGHT];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalKnight,
                        _EvalKnight(pos, c, pHash));
#ifdef EVAL_DUMP
        Trace("After enemy N at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Bishops.
    bb = pos->bbPieces[uColor][BISHOP];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalBishop,
                        _EvalBishop(pos, c, pHash, bbEnemyRQK[xColor]));
#ifdef EVAL_DUMP
        Trace("After our B at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Enemy bishops.
    bb = pos->bbPieces[xColor][BISHOP];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalBishop,
                         _EvalBishop(pos, c, pHash, bbEnemyRQK[uColor]));
#ifdef EVAL_DUMP
        Trace("After enemy B at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Both colors' knight+bishop passes are complete now -- safe to
    // build both colors' "unsafe for rook" masks once, here, instead of
    // every rook rebuilding its own color's mask from scratch.
    bbUnsafeForRook[WHITE] = pos->bbPawnAttacks[BLACK] |
        pos->bbMinorAttacks[BLACK];
    bbUnsafeForRook[BLACK] = pos->bbPawnAttacks[WHITE] |
        pos->bbMinorAttacks[WHITE];

    // Rooks.
    bb = pos->bbPieces[uColor][ROOK];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalRook,
                        _EvalRook(pos, c, pHash, bbEnemyQK[xColor],
                                  bbUnsafeForRook[uColor]));
#ifdef EVAL_DUMP
        Trace("After our R at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Enemy rooks.
    bb = pos->bbPieces[xColor][ROOK];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalRook,
                        _EvalRook(pos, c, pHash, bbEnemyQK[uColor],
                                  bbUnsafeForRook[xColor]));
#ifdef EVAL_DUMP
        Trace("After enemy R at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Both colors' pawn/minor/rook passes are complete now -- safe to
    // build both colors' "unsafe for queen" masks once, here, instead
    // of every queen rebuilding its own color's mask from scratch (most
    // positions only have one queen per side anyway, so this mainly
    // pays off on promoted-extra-queen positions, but it's free either
    // way).
    bbUnsafeForQueen[WHITE] = pos->bbPawnAttacks[BLACK] |
        pos->bbMinorAttacks[BLACK] |
        pos->bbRookAttacks[BLACK] |
        (g_KingAttacksBB[pos->cKingSq[BLACK]] &
         ~(pos->bbPawnAttacks[WHITE] |
           pos->bbMinorAttacks[WHITE] |
           pos->bbRookAttacks[WHITE]));
    bbUnsafeForQueen[BLACK] = pos->bbPawnAttacks[WHITE] |
        pos->bbMinorAttacks[WHITE] |
        pos->bbRookAttacks[WHITE] |
        (g_KingAttacksBB[pos->cKingSq[WHITE]] &
         ~(pos->bbPawnAttacks[BLACK] |
           pos->bbMinorAttacks[BLACK] |
           pos->bbRookAttacks[BLACK]));

    // Our queen(s).
    bb = pos->bbPieces[uColor][QUEEN];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalQueen,
                        _EvalQueen(pos, c, pHash, bbEnemyQK[xColor],
                                   bbUnsafeForQueen[uColor]));
#ifdef EVAL_DUMP
        Trace("After our Q at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Enemy queen(s).
    bb = pos->bbPieces[xColor][QUEEN];
    while (bb)
    {
        u = FastFirstBit(bb) - 1;
        bb &= (bb - 1);
        c = BIT_NUMBER_TO_COOR(u);
        TIMED_EVAL_CALL(ctx, u64CyclesEvalQueen,
                        _EvalQueen(pos, c, pHash, bbEnemyQK[uColor],
                                   bbUnsafeForQueen[xColor]));
#ifdef EVAL_DUMP
        Trace("After enemy Q at %s:\n%d\t\t%d\t\t(%d for %s)\n",
              CoorToString(c),
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // Evaluate the two kings last.
    c = KingPosition(pos, uColor);
#ifdef DEBUG
    ASSERT(IS_ON_BOARD(c));
    {
        PIECE pDebugKing = pos->rgSquare[c].pPiece;
        ASSERT(IS_VALID_PIECE(pDebugKing));
        ASSERT(GET_COLOR(pDebugKing) == uColor);
        ASSERT(IS_KING(pDebugKing));
    }
#endif
    TIMED_EVAL_CALL(ctx, u64CyclesEvalKing,
                     _EvalKing(pos, c, pHash, ctx));
#ifdef EVAL_DUMP
    Trace("After our K at %s:\n%d\t\t%d\t\t(%d for %s)\n",
          CoorToString(c),
          pos->iScore[WHITE], pos->iScore[BLACK],
          (pos->iScore[uColor] - pos->iScore[xColor]),
          COLOR_NAME(uColor)
    );
#endif

    c = KingPosition(pos, xColor);
#ifdef DEBUG
    ASSERT(IS_ON_BOARD(c));
    {
        PIECE pDebugKing = pos->rgSquare[c].pPiece;
        ASSERT(IS_VALID_PIECE(pDebugKing));
        ASSERT(GET_COLOR(pDebugKing) == xColor);
        ASSERT(IS_KING(pDebugKing));
    }
#endif
    TIMED_EVAL_CALL(ctx, u64CyclesEvalKing,
                     _EvalKing(pos, c, pHash, ctx));
#ifdef EVAL_DUMP
    Trace("After enemy K at %s:\n%d\t\t%d\t\t(%d for %s)\n",
          CoorToString(c),
          pos->iScore[WHITE], pos->iScore[BLACK],
          (pos->iScore[uColor] - pos->iScore[xColor]),
          COLOR_NAME(uColor)
    );
#endif

    // Now that we have the whole attack table generated, think about
    // passed pawns identified by the pawn eval routine again.  Also
    // see if the side not on move has a trapped piece.
#ifdef EVAL_TIME
    UINT64 u64PostLazyMiscTimer = SystemReadTimeStampCounter();
#endif
    bb = (pHash->bbPasserLocations[WHITE] | pHash->bbPasserLocations[BLACK]);
    if (0 != bb)
    {
        _ReEvalPassers(pos, pHash);
#ifdef EVAL_DUMP
        Trace("After re-eval passers:\n%d\t\t%d\t\t(%d for %s)\n",
              pos->iScore[WHITE], pos->iScore[BLACK],
              (pos->iScore[uColor] - pos->iScore[xColor]),
              COLOR_NAME(uColor)
        );
#endif
    }

    // _EvalLookForDanger/_EvalTrappedPieces only ever *add* a hint
    // when they find one; a full eval that finds nothing this time
    // would otherwise leave a stale, unrelated hint from an earlier
    // visit to this ply sitting here.  Clear this ply's self-danger
    // slots first so a clean full eval reliably means a clean slate.
    ctx->cEnprise[ctx->uPly][0] = ctx->cEnprise[ctx->uPly][1] = ILLEGAL_COOR;
    ctx->cTrapped[ctx->uPly] = ILLEGAL_COOR;
    //_EvalLookForDanger(ctx);
    _EvalTrappedPieces(ctx);

    // TODO: endgame-specific knowledge?  e.g. B over N in an endgame
    // with 2 pawn wings?

    // Roll in the reduced material down scaler terms (aggregate).
    ASSERT(pos->iReducedMaterialDownScaler[BLACK] > -200);
    ASSERT(pos->iReducedMaterialDownScaler[BLACK] < +200);
    pos->iScore[BLACK] += (
        pos->iReducedMaterialDownScaler[BLACK] *
        (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[BLACK]]
    ) / 8;
    ASSERT(pos->iReducedMaterialDownScaler[WHITE] > -200);
    ASSERT(pos->iReducedMaterialDownScaler[WHITE] < +200);
    pos->iScore[WHITE] += (
        pos->iReducedMaterialDownScaler[WHITE] *
        (SCORE)REDUCED_MATERIAL_DOWN_SCALER[pos->uArmyScaler[WHITE]]
    ) / 8;

#ifdef EVAL_TIME
    ctx->sCounters.tree.u64CyclesEvalPostLazyMisc +=
        (SystemReadTimeStampCounter() - u64PostLazyMiscTimer);
#endif
#ifdef EVAL_DUMP
    Trace("After all pieces:\n%d\t\t%d\t\t(%d for %s)\n",
          pos->iScore[WHITE], pos->iScore[BLACK],
          (pos->iScore[uColor] - pos->iScore[xColor]),
          COLOR_NAME(uColor)
    );
#endif

    // Almost done
    iScoreForSideToMove = (pos->iScore[uColor] - pos->iScore[xColor]);

#ifdef DUMP_RESIDUAL_SAMPLES
    // One CSV-ish line per full Eval() call: combined army scaler
    // (total pieces proxy), signed army-scaler diff (piece-balance
    // proxy), and each side's isolated residual (mobility/trapped/
    // misc, with material/pawns/passers/bad-trade/bishop-pairs/king
    // safety already subtracted out via the baseline captured after
    // bishop pairs, above, and the real per-side king score). Sampled
    // before EvalLookForDrawishSituations' squash below, since that
    // squash is a separate, already-handled mechanism, not part of
    // what iResidualP98 is meant to estimate.
    {
        SCORE iResidualWhite = pos->iScore[WHITE] - iResidualBaselineWhite -
            ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE];
        SCORE iResidualBlack = pos->iScore[BLACK] - iResidualBaselineBlack -
            ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK];

        // Histogram, not a raw per-sample Trace -- at 30k-position
        // scale a raw dump would run into the billions of lines (a
        // 200-position sample alone produced 8.76M). Bucketed by OWN
        // army scaler (color-blind: each side contributes its own
        // row), same convention as the earlier ad hoc Python analysis.
        _RecordResidualSample(MINU(7, pos->uArmyScaler[WHITE] / 4),
                              (INT)iResidualWhite);
        _RecordResidualSample(MINU(7, pos->uArmyScaler[BLACK] / 4),
                              (INT)iResidualBlack);

        // Super-lazy-scoped residual: same idea, but relative to
        // super-lazy's own (material-only) baseline, so pawns/passers/
        // bad-trade/bishop-pairs are included instead of excluded --
        // this is what super-lazy's own margin_a/margin_b construction
        // actually needs (2026-09-17).
        {
            SCORE iSLResidualWhite = pos->iScore[WHITE] -
                iSuperLazyResidualBaselineWhite -
                ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE];
            SCORE iSLResidualBlack = pos->iScore[BLACK] -
                iSuperLazyResidualBaselineBlack -
                ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK];
            _RecordSuperLazyResidualSample(MINU(7, pos->uArmyScaler[WHITE] / 4),
                                           (INT)iSLResidualWhite);
            _RecordSuperLazyResidualSample(MINU(7, pos->uArmyScaler[BLACK] / 4),
                                           (INT)iSLResidualBlack);
        }

        // Outlier FEN capture -- thresholds picked comfortably beyond
        // the p10/p90 range seen in every bucket of the 200-position
        // smoke sample (worst bucket's p90/p10 topped out around
        // +/-230), so this only fires for genuine tail events worth
        // going back and looking at by hand, not routine variance.
        // 2026-09-17: capped -- the 200-position sample this threshold
        // was tuned against never came close to needing a cap, but the
        // far larger/more-varied 30k stratified pool hits this on a
        // real fraction of nodes and produced 2GB+ of Trace output
        // before filling /tmp on the first attempt. The histogram data
        // above is unaffected by this cap; only the (nice-to-have,
        // not essential) worked-example FEN capture is limited.
        if (((abs((int)iResidualWhite) > 250) || (abs((int)iResidualBlack) > 250)) &&
            (g_uResidualOutliersPrinted < 200))
        {
            CHAR *pszOutlierFen = PositionToFen(pos);
            if (NULL != pszOutlierFen)
            {
                Trace("RESIDUAL_OUTLIER_FEN resW=%d resB=%d fen=%s\n",
                      (int)iResidualWhite, (int)iResidualBlack, pszOutlierFen);
                SystemFreeMemory(pszOutlierFen);
                g_uResidualOutliersPrinted++;
            }
        }

        // Same color-blind, per-side idea for king safety: each side's
        // REAL, already-scaled king contribution (ctx->sPlyInfo[...]
        // .iKingScore[color] -- scaled by REDUCED_MATERIAL_DOWN_SCALER
        // inside _EvalKing already, so this is the true realized
        // magnitude, not the pre-scale raw value the old iKingSwingP90
        // table was fit against), paired with the ATTACKER's own army
        // (the side actually threatening that king), not the king
        // owner's. Bucketing directly by attacker army this way means
        // no runtime rescale step is needed at all in the redesign --
        // the bucketing itself carries the army dependence.
        _RecordKingSafetySample(MINU(7, pos->uArmyScaler[BLACK] / 4),
                               (INT)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]);
        _RecordKingSafetySample(MINU(7, pos->uArmyScaler[WHITE] / 4),
                               (INT)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]);

        // Same idea as the residual outlier capture above -- threshold
        // picked beyond the p10/p90 range seen in every king-safety
        // bucket (worst bucket topped out around +/-160).
        if (((abs((int)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]) > 200) ||
             (abs((int)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]) > 200)) &&
            (g_uKingSafetyOutliersPrinted < 200))
        {
            CHAR *pszOutlierFen = PositionToFen(pos);
            if (NULL != pszOutlierFen)
            {
                Trace("KINGSAFETY_OUTLIER_FEN kingW=%d kingB=%d fen=%s\n",
                      (int)ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE],
                      (int)ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK],
                      pszOutlierFen);
                SystemFreeMemory(pszOutlierFen);
                g_uKingSafetyOutliersPrinted++;
            }
        }
    }
#endif

    // Drive drawish situations towards the draw score. Usually a
    // no-op fetch here (sDrawishFacts already computed by the
    // regular-lazy attempt above) -- only does real work when that
    // attempt was skipped entirely (bare-king/low-material nodes,
    // see LAZY_EVAL_MIN_MATERIAL/fBareKingEitherSide above), in which
    // case this is that node's only call site.
    TIMED_EVAL_CALL(ctx, u64CyclesEvalDrawish,
                    (_EnsureDrawishFactsComputed(pos, uColor, &sDrawishFacts),
                     EvalLookForDrawishSituations(pos, &iScoreForSideToMove,
                                                  &sDrawishFacts)));

    // Adjust dynamic positional component.  Unlike the lazy-exit
    // margins above (always >= 0 by construction), this can go
    // negative -- a side whose positional terms (king safety, pawn
    // structure, hanging pieces, ...) net worse than its raw material
    // gets a genuinely negative value here.  search.c's futility
    // margin (FUTILITY_BASE_MARGIN_BY_SOURCE[side's tier] +
    // piPositional[side]) deliberately lets that shrink the margin --
    // a positionally-bad side is less likely to be saved by an
    // unexamined quiet move -- but floor it so one bad eval term
    // can't collapse the margin arbitrarily far; this only ever runs
    // on the full-eval exit, so -FUTILITY_BASE_MARGIN_FULL/2 (not the
    // lazy/super-lazy tiers) caps the damage at half of that tier's
    // base.
    if (NULL != piPositional)
    {
        (*piPositional)[WHITE] =
            MAX(pos->iScore[WHITE] -
                (SCORE)(PawnMaterial(pos, WHITE) + pos->uNonPawnMaterial[WHITE]),
                -(FUTILITY_BASE_MARGIN_FULL / 2));
        (*piPositional)[BLACK] =
            MAX(pos->iScore[BLACK] -
                (SCORE)(PawnMaterial(pos, BLACK) + pos->uNonPawnMaterial[BLACK]),
                -(FUTILITY_BASE_MARGIN_FULL / 2));
        ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_FULL;
    }
    g_Options.iLastEvalScore = iScoreForSideToMove;

#ifdef CALIBRATE_MARGIN_SAFETY
    if (TRUE == fWouldHaveExitedSuperLazy)
    {
        //
        // Real (non-calibration) code checks super-lazy first and
        // returns immediately on a hit -- so if this call would *also*
        // have satisfied the regular lazy condition below, super-lazy
        // is still what a normal build actually returns. Record/
        // restore this one, not the regular-lazy save in the other
        // branch.
        //
        // Direction matters: for an alpha-side exit (saved score below
        // alpha), only an *upward* real swing is dangerous -- it's the
        // one that could pull the score back over alpha. A downward
        // swing just makes the verdict even more clearly correct. Same
        // in reverse for a beta-side exit. abs() was conflating both
        // directions, so "exceeded" was really an upper bound on real
        // unsoundness, not a measurement of it.
        RecordSuperLazyMarginSafetySwing(
            pos,
            (iSavedSuperLazyScore < iAlpha)
                ? MAX0(iScoreForSideToMove - iSavedSuperLazyScore)
                : MAX0(iSavedSuperLazyScore - iScoreForSideToMove),
            iSavedSuperLazyMarginUsed);
        iScoreForSideToMove = iSavedSuperLazyScore;
        if (NULL != piPositional)
        {
            ULONG uWhiteBucket = MINU(7, pos->uArmyScaler[WHITE] / 4);
            ULONG uBlackBucket = MINU(7, pos->uArmyScaler[BLACK] / 4);
            (*piPositional)[WHITE] =
                iKingP50ByAttackerArmyOnly[uBlackBucket] +
                iSuperLazyResidualP50ByOwnArmy[uWhiteBucket];
            (*piPositional)[BLACK] =
                iKingP50ByAttackerArmyOnly[uWhiteBucket] +
                iSuperLazyResidualP50ByOwnArmy[uBlackBucket];
            // CALIBRATE_MARGIN_SAFETY builds: the FULL tag set above
            // reflects the fallthrough that just ran for measurement
            // purposes, not what a normal build actually returns here
            // -- fix it back up to match the restored (super-lazy)
            // values.
            ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_SUPERLAZY;
        }
    }
    else if (TRUE == fWouldHaveExited)
    {
        //
        // The real swing: how far the true, full-eval score actually
        // ended up from the lazy-exit score this node would have
        // returned. RecordMarginSafetySwing buckets this by material;
        // its max (not just p90) is the number that answers "how
        // large would LAZY_EVAL_BASE_MARGIN have had to be before an
        // exit here would have been unsound."
        //
        // Same directional fix as the super-lazy branch above.
        RecordMarginSafetySwing(
            pos,
            (iSavedLazyScore < iAlpha)
                ? MAX0(iScoreForSideToMove - iSavedLazyScore)
                : MAX0(iSavedLazyScore - iScoreForSideToMove),
            iSavedLazyPositional);
        //
        // Restore exactly what a normal build would have returned --
        // this measurement must not change real search behavior.
        //
        iScoreForSideToMove = iSavedLazyScore;
        if (NULL != piPositional)
        {
            (*piPositional)[WHITE] = iSavedLazyPositionalWhite;
            (*piPositional)[BLACK] = iSavedLazyPositionalBlack;
            ctx->sPlyInfo[ctx->uPly].uLastPositionalSource = EVAL_POSITIONAL_SOURCE_LAZY;
        }
    }
#endif

#ifdef EVAL_TIME
    ctx->sCounters.tree.u64CyclesFullEvalExit += (SystemReadTimeStampCounter() -
                                                   uTimer);
    ctx->sCounters.tree.u64CyclesInEval += (SystemReadTimeStampCounter() -
                                            uTimer);
#endif
    INC(ctx->sCounters.tree.u64FullEvals);
    g_u64FullEvalsByBucket[_MaterialBucket(pos)]++;

 end:
    ASSERT(IS_VALID_SCORE(iScoreForSideToMove));
    ASSERT((iScoreForSideToMove > -NMATE) &&
           (iScoreForSideToMove < +NMATE));
    ASSERT(abs(ctx->sPlyInfo[ctx->uPly].iKingScore[BLACK]) < 700);
    ASSERT(abs(ctx->sPlyInfo[ctx->uPly].iKingScore[WHITE]) < 700);

    return(iScoreForSideToMove);
}