summaryrefslogtreecommitdiff
path: root/eval.c
blob: 54d5b696ebc257b6878bd30c2df6981930fea342 (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
/*
 * eval.c
 *
 * by Gary Wong <gtw@gnu.org>, 1998, 1999, 2000, 2001, 2002.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 3 or later of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: eval.c,v 1.477 2018/04/28 22:14:46 plm Exp $
 */

#include "config.h"
#include "backgammon.h"
#include <glib.h>
#include <glib/gstdio.h>
#include <locale.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include "isaac.h"
#include <md5.h>
#include "bearoffgammon.h"
#include "positionid.h"
#include "matchid.h"
#include "matchequity.h"
#include "format.h"
#include "simd.h"
#include "multithread.h"
#include "util.h"
#include "lib/simd.h"
#include "glib-ext.h"

typedef void (*classstatusfunc) (char *szOutput);
typedef int (*cfunc) (const void *, const void *);

/* Race inputs */
enum {
    /* In a race position, bar and the 24 points are always empty, so only */
    /* 23*4 (92) are needed */

    /* (0 <= k < 14), RI_OFF + k = */
    /*                       1 if exactly k+1 checkers are off, 0 otherwise */

    RI_OFF = 92,

    /* Number of cross-overs by outside checkers */

    RI_NCROSS = 92 + 14,

    HALF_RACE_INPUTS
};


/* Contact inputs -- see Berliner for most of these */
enum {
    /* n - number of checkers off
     * 
     * off1 -  1         n >= 5
     * n/5       otherwise
     * 
     * off2 -  1         n >= 10
     * (n-5)/5   n < 5 < 10
     * 0         otherwise
     * 
     * off3 -  (n-10)/5  n > 10
     * 0         otherwise
     */

    I_OFF1, I_OFF2, I_OFF3,

    /* Minimum number of pips required to break contact.
     * 
     * For each checker x, N(x) is checker location,
     * C(x) is max({forall o : N(x) - N(o)}, 0)
     * 
     * Break Contact : (sum over x of C(x)) / 152
     * 
     * 152 is dgree of contact of start position.
     */
    I_BREAK_CONTACT,

    /* Location of back checker (Normalized to [01])
     */
    I_BACK_CHEQUER,

    /* Location of most backward anchor.  (Normalized to [01])
     */
    I_BACK_ANCHOR,

    /* Forward anchor in opponents home.
     * 
     * Normalized in the following way:  If there is an anchor in opponents
     * home at point k (1 <= k <= 6), value is k/6. Otherwise, if there is an
     * anchor in points (7 <= k <= 12), take k/6 as well. Otherwise set to 2.
     * 
     * This is an attempt for some continuity, since a 0 would be the "same" as
     * a forward anchor at the bar.
     */
    I_FORWARD_ANCHOR,

    /* Average number of pips opponent loses from hits.
     * 
     * Some heuristics are required to estimate it, since we have no idea what
     * the best move actually is.
     * 
     * 1. If board is weak (less than 3 anchors), don't consider hitting on
     * points 22 and 23.
     * 2. Don't break anchors inside home to hit.
     */
    I_PIPLOSS,

    /* Number of rolls that hit at least one checker.
     */
    I_P1,

    /* Number of rolls that hit at least two checkers.
     */
    I_P2,

    /* How many rolls permit the back checker to escape (Normalized to [01])
     */
    I_BACKESCAPES,

    /* Maximum containment of opponent checkers, from our points 9 to op back 
     * checker.
     * 
     * Value is (1 - n/36), where n is number of rolls to escape.
     */
    I_ACONTAIN,

    /* Above squared */
    I_ACONTAIN2,

    /* Maximum containment, from our point 9 to home.
     * Value is (1 - n/36), where n is number of rolls to escape.
     */
    I_CONTAIN,

    /* Above squared */
    I_CONTAIN2,

    /* For all checkers out of home, 
     * sum (Number of rolls that let x escape * distance from home)
     * 
     * Normalized by dividing by 3600.
     */
    I_MOBILITY,

    /* One sided moment.
     * Let A be the point of weighted average: 
     * A = sum of N(x) for all x) / nCheckers.
     * 
     * Then for all x : A < N(x), M = (average (N(X) - A)^2)
     * 
     * Diveded by 400 to normalize. 
     */
    I_MOMENT2,

    /* Average number of pips lost when on the bar.
     * Normalized to [01]
     */
    I_ENTER,

    /* Probablity of one checker not entering from bar.
     * 1 - (1 - n/6)^2, where n is number of closed points in op home.
     */
    I_ENTER2,

    I_TIMING,

    I_BACKBONE,

    I_BACKG,

    I_BACKG1,

    I_FREEPIP,

    I_BACKRESCAPES,

    MORE_INPUTS
};

#define MINPPERPOINT 4

#define NUM_INPUTS ((25 * MINPPERPOINT + MORE_INPUTS) * 2)
#define NUM_RACE_INPUTS ( HALF_RACE_INPUTS * 2 )
#define NUM_PRUNING_INPUTS (25 * MINPPERPOINT * 2)


#if !defined(LOCKING_VERSION)

f_FindnSaveBestMoves FindnSaveBestMoves = FindnSaveBestMovesNoLocking;
f_FindBestMove FindBestMove = FindBestMoveNoLocking;
f_EvaluatePosition EvaluatePosition = EvaluatePositionNoLocking;
f_ScoreMove ScoreMove = ScoreMoveNoLocking;
f_GeneralCubeDecisionE GeneralCubeDecisionE = GeneralCubeDecisionENoLocking;
f_GeneralEvaluationE GeneralEvaluationE = GeneralEvaluationENoLocking;

#define FindnSaveBestMoves FindnSaveBestMovesNoLocking
#define FindBestMove FindBestMoveNoLocking
#define EvaluatePosition EvaluatePositionNoLocking
#define ScoreMove ScoreMoveNoLocking
#define GeneralCubeDecisionE GeneralCubeDecisionENoLocking
#define GeneralEvaluationE GeneralEvaluationENoLocking
#define EvaluatePositionCache EvaluatePositionCacheNoLocking
#define FindBestMovePlied FindBestMovePliedNoLocking
#define GeneralEvaluationEPlied GeneralEvaluationEPliedNoLocking
#define EvaluatePositionCubeful3 EvaluatePositionCubeful3NoLocking
#define ScoreMoves ScoreMovesNoLocking
#define ScoreMovesPruned ScoreMovesPrunedNoLocking
#define FindBestMoveInEval FindBestMoveInEvalNoLocking
#define GeneralEvaluationEPliedCubeful GeneralEvaluationEPliedCubefulNoLocking
#define EvaluatePositionCubeful4 EvaluatePositionCubeful4NoLocking
#define CacheAdd CacheAddNoLocking
#define CacheLookup CacheLookupNoLocking

static int EvaluatePositionCache(NNState * nnStates, const TanBoard anBoard, float arOutput[],
                                 cubeinfo * const pci, const evalcontext * pecx, int nPlies, positionclass pc);

static int FindBestMovePlied(int anMove[8], int nDice0, int nDice1,
                             TanBoard anBoard, const cubeinfo * pci,
                             const evalcontext * pec, int nPlies, movefilter aamf[MAX_FILTER_PLIES][MAX_FILTER_PLIES]);

static int anEscapes[0x1000];
static int anEscapes1[0x1000];

static int anPoint[16] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

neuralnet nnContact, nnRace, nnCrashed;

neuralnet nnpContact, nnpRace, nnpCrashed;

bearoffcontext *pbcOS = NULL;
bearoffcontext *pbcTS = NULL;
bearoffcontext *pbc1 = NULL;
bearoffcontext *pbc2 = NULL;
bearoffcontext *apbcHyper[3] = { NULL, NULL, NULL };

evalCache cEval;
evalCache cpEval;
unsigned int cCache;
int fInterrupt = FALSE;
int fMatchCancelled = FALSE;

/* variation of backgammon used by gnubg */

bgvariation bgvDefault = VARIATION_STANDARD;

/* the number of chequers for the variations */

int anChequers[NUM_VARIATIONS] = { 15, 15, 1, 2, 3 };

const char *aszVariations[NUM_VARIATIONS] = {
    N_("Standard backgammon"),
    N_("Nackgammon"),
    N_("1-chequer hypergammon"),
    N_("2-chequer hypergammon"),
    N_("3-chequer hypergammon")
};

const char *aszVariationCommands[NUM_VARIATIONS] = {
    "standard",
    "nackgammon",
    "1-chequer-hypergammon",
    "2-chequer-hypergammon",
    "3-chequer-hypergammon"
};

cubeinfo ciCubeless = { 1, 0, 0, 0, {0, 0}, FALSE, FALSE, FALSE,
{1.0, 1.0, 1.0, 1.0}, VARIATION_STANDARD
};

const char *aszEvalType[] = {
    N_("No evaluation"),
    N_("Neural net evaluation"),
    N_("Rollout")
};

evalcontext ecBasic = { FALSE, 0, FALSE, TRUE, 0.0 };

/* defaults for the filters  - 0 ply uses no filters */

#include "movefilters.inc"

movefilter defaultFilters[MAX_FILTER_PLIES][MAX_FILTER_PLIES] = MOVEFILTER_NORMAL;


/* Random context, for generating non-deterministic noisy evaluations. */
static randctx rc;

/*
 * predefined settings 
 */

const char *aszSettings[NUM_SETTINGS] = {
    N_("setting|beginner"),
    N_("setting|casual play"),
    N_("setting|intermediate"),
    N_("setting|advanced"),
    N_("setting|expert"),
    N_("setting|world class"),
    N_("setting|supremo"),
    N_("setting|grandmaster"),
    N_("setting|4ply")
};

/* which evaluation context does the predefined settings use */
evalcontext aecSettings[NUM_SETTINGS] = {
    {TRUE, 0, FALSE, TRUE, 0.060f},     /* beginner */
    {TRUE, 0, FALSE, TRUE, 0.050f},     /* casual player */
    {TRUE, 0, FALSE, TRUE, 0.040f},     /* intermediate */
    {TRUE, 0, FALSE, TRUE, 0.015f},     /* advanced */
    {TRUE, 0, FALSE, TRUE, 0.0f},       /* expert */
    {TRUE, 2, TRUE, TRUE, 0.0f},        /* world class */
    {TRUE, 2, TRUE, TRUE, 0.0f},        /* supremo */
    {TRUE, 3, TRUE, TRUE, 0.0f},        /* grand master */
    {TRUE, 4, TRUE, TRUE, 0.0f},        /* 4ply */
};

/* which move filter does the predefined settings use */
int aiSettingsMoveFilter[NUM_SETTINGS] = {
    -1,                         /* beginner: n/a */
    -1,                         /* casual play: n/a */
    -1,                         /* intermediate: n/a */
    -1,                         /* advanced: n/a */
    -1,                         /* expert: n/a */
    2,                          /* wc: normal */
    3,                          /* supremo: large */
    3,                          /* grandmaster: large */
    3,                          /* 4ply: large */
};

/* the predefined move filters */

const char *aszMoveFilterSettings[NUM_MOVEFILTER_SETTINGS] = {
    N_("Tiny"),
    N_("Narrow"),
    N_("Normal"),
    N_("Large"),
    N_("Huge")
};

movefilter aaamfMoveFilterSettings[NUM_MOVEFILTER_SETTINGS][MAX_FILTER_PLIES][MAX_FILTER_PLIES] = {
    MOVEFILTER_TINY,
    MOVEFILTER_NARROW,
    MOVEFILTER_NORMAL,
    MOVEFILTER_LARGE,
    MOVEFILTER_HUGE
};


const char *aszDoubleTypes[NUM_DOUBLE_TYPES] = {
    N_("doubletype|Double"),
    N_("doubletype|Beaver"),
    N_("doubletype|Raccoon")
};

/* parameters for EvalEfficiency */

static float rTSCubeX = 0.6f;   /* for match play only */
float rOSCubeX = 0.6f;
float rRaceFactorX = 0.00125f;
float rRaceCoefficientX = 0.55f;
float rRaceMax = 0.7f;
float rRaceMin = 0.6f;
float rCrashedX = 0.68f;
float rContactX = 0.68f;


#ifdef HAVE___BUILTIN_CLZ
static inline int
msb32(int n)
{
    return 31 - __builtin_clz(n);  /* or __builtin_clz() ^ 31 */
}
#else
/* from rosettacode.org */
static inline int
msb32(int n)
{
    int b = 0;
#define step(x) if (n >= 1 << x) b += x, n >>= x
    step(16);
    step(8);
    step(4);
    step(2);
    step(1);
#undef step
    return b;
}
#endif

static void
ComputeTable0(void)
{
    int i, c, n0, n1;

    for (i = 0; i < 0x1000; i++) {
        c = 0;

        for (n0 = 0; n0 <= 5; n0++)
            for (n1 = 0; n1 <= n0; n1++)
                if (!(i & (1 << (n0 + n1 + 1))) && !((i & (1 << n0)) && (i & (1 << n1))))
                    c += (n0 == n1) ? 1 : 2;

        anEscapes[i] = c;
    }
}

static int
Escapes(const unsigned int anBoard[25], int n)
{

    int i, af = 0, m;

    m = (n < 12) ? n : 12;

    for (i = 0; i < m; i++)
        af |= (anPoint[anBoard[24 + i - n]] << i);

    return anEscapes[af];
}

static void
ComputeTable1(void)
{
    int i, c, n0, n1, low;

    anEscapes1[0] = 0;

    for (i = 1; i < 0x1000; i++) {
        c = 0;

        low = 0;
        while (!(i & (1 << low))) {
            ++low;
        }

        for (n0 = 0; n0 <= 5; n0++)
            for (n1 = 0; n1 <= n0; n1++) {

                if ((n0 + n1 + 1 > low) && !(i & (1 << (n0 + n1 + 1))) && !((i & (1 << n0)) && (i & (1 << n1)))) {
                    c += (n0 == n1) ? 1 : 2;
                }
            }

        anEscapes1[i] = c;
    }
}

static int
Escapes1(const unsigned int anBoard[25], int n)
{

    int i, af = 0, m;

    m = (n < 12) ? n : 12;

    for (i = 0; i < m; i++)
        af |= (anPoint[anBoard[24 + i - n]] << i);

    return anEscapes1[af];
}


static void
ComputeTable(void)
{
    ComputeTable0();
    ComputeTable1();
}

static void
DestroyWeights(void)
{
    NeuralNetDestroy(&nnContact);
    NeuralNetDestroy(&nnCrashed);
    NeuralNetDestroy(&nnRace);

    NeuralNetDestroy(&nnpContact);
    NeuralNetDestroy(&nnpCrashed);
    NeuralNetDestroy(&nnpRace);
}

extern int
EvalShutdown(void)
{

    int i;

    /* close bearoff databases */

    BearoffClose(pbc1);
    BearoffClose(pbc2);
    BearoffClose(pbcOS);
    BearoffClose(pbcTS);
    for (i = 0; i < 3; ++i)
        BearoffClose(apbcHyper[i]);

    /* destroy neural nets */

    DestroyWeights();

    /* destroy cache */

    CacheDestroy(&cEval);
    CacheDestroy(&cpEval);

    return 0;

}

static int
binary_weights_failed(char *filename, FILE * weights)
{
    float r;

    if (!weights) {
        g_print(_("couldn't open %s"), filename);
        g_print("\n");
        return -1;
    }
    if (fread(&r, sizeof r, 1, weights) < 1) {
        g_print(_("couldn't read %s"), filename);
        g_print("\n");
        return -2;
    }
    if (r != WEIGHTS_MAGIC_BINARY) {
        g_print(_("%s is not a weights file"), filename);
        g_print("\n");
        return -3;
    }
    if (fread(&r, sizeof r, 1, weights) < 1) {
        g_print(_("couldn't read %s"), filename);
        g_print("\n");
        return -4;
    }
    if (r != WEIGHTS_VERSION_BINARY) {
        char buf[20];
        sprintf(buf, "%.2f", r);
        g_print(_("weights file %s, has incorrect version (%s), expected (%s)"), filename, buf, WEIGHTS_VERSION);
        g_print("\n");
        return -5;
    }

    return 0;
}

static int
weights_failed(char *filename, FILE * weights)
{
    char file_version[16];
    if (!weights) {
        g_print(_("couldn't open %s"), filename);
        g_print("\n");
        return -1;
    }

    if (fscanf(weights, "GNU Backgammon %15s\n", file_version) != 1) {
        g_print(_("%s is not a weights file"), filename);
        g_print("\n");
        return -2;
    }
    if (strcmp(file_version, WEIGHTS_VERSION)) {
        g_print(_("weights file %s, has incorrect version (%s), expected (%s)"),
                filename, file_version, WEIGHTS_VERSION);
        g_print("\n");
        return -3;
    }
    return 0;
}

extern void
EvalInitialise(char *szWeights, char *szWeightsBinary, int fNoBearoff, void (*pfProgress) (unsigned int))
{
    FILE *pfWeights = NULL;
    int i, fReadWeights = FALSE;
    static int fInitialised = FALSE;
    char *gnubg_bearoff;
    char *gnubg_bearoff_os;
#if defined(USE_SIMD_INSTRUCTIONS)
    int result, simderror = TRUE;
#endif

    if (!fInitialised) {
#if defined(USE_SIMD_INSTRUCTIONS)
        result = SIMD_Supported();
        switch (result) {
        case -1:
            outputerrf(_("Can't check for SIMD support\n"));
            break;
        case -2:
            outputerrf(_("No cpuid check available\n"));
            break;
        case 0:
            /* No SIMD support */
            break;
        case 1:
            /* SIMD support */
            simderror = FALSE;
            break;
        default:
            outputerrf(_("Unknown error while doing SIMD support test\n"));
        }

        if (simderror) {
#if defined(USE_AVX)
            outputerrf(_
                       ("\nThis version of GNU Backgammon is compiled with AVX support but this machine does not support AVX\n"));
#else
            outputerrf(_
                       ("\nThis version of GNU Backgammon is compiled with SSE support but this machine does not support SSE\n"));
#endif
            exit(EXIT_FAILURE);
        }
#endif
        cCache = 0x1 << CACHE_SIZE_DEFAULT;
        if (CacheCreate(&cEval, cCache)) {
            PrintError("CacheCreate");
            return;
        }

        if (CacheCreate(&cpEval, 0x1 << 16)) {
            PrintError("CacheCreate");
            return;
        }

        ComputeTable();

        rc.randrsl[0] = (ub4) time(NULL);
        for (i = 0; i < RANDSIZ; i++)
            rc.randrsl[i] = rc.randrsl[0];
        irandinit(&rc, TRUE);

        fInitialised = TRUE;
    }

    if (!fNoBearoff) {
        gnubg_bearoff_os = BuildFilename("gnubg_os0.bd");
        if (!pbc1)
            pbc1 = BearoffInit(gnubg_bearoff_os, BO_IN_MEMORY|BO_MUST_BE_ONE_SIDED, NULL);
        g_free(gnubg_bearoff_os);

        if (!pbc1)
            pbc1 = BearoffInit(NULL, BO_HEURISTIC, pfProgress);

        /* read two-sided db from gnubg.bd */
        gnubg_bearoff = BuildFilename("gnubg_ts0.bd");
        pbc2 = BearoffInit(gnubg_bearoff, BO_IN_MEMORY | BO_MUST_BE_TWO_SIDED, NULL);
        g_free(gnubg_bearoff);

        if (!pbc2)
            fprintf(stderr,
                    "\n***WARNING***\n\n"
                    "GNU Backgammon will not use the two-sided bearoff\n"
                    "database since the gnubg_ts0.bd could not be found.\n"
                    "You should obtain this file or generate it yourself\n"
                    "with the command: makebearoff -t 6x6 -f gnubg_ts0.bd\n"
                    "You can also generate other bearoff databases; see\n" "README for more details\n\n");

        gnubg_bearoff_os = BuildFilename("gnubg_os.bd");
        /* init one-sided db */
        pbcOS = BearoffInit(gnubg_bearoff_os, BO_IN_MEMORY|BO_MUST_BE_ONE_SIDED, NULL);
        g_free(gnubg_bearoff_os);

        gnubg_bearoff = BuildFilename("gnubg_ts.bd");
        /* init two-sided db */
        pbcTS = BearoffInit(gnubg_bearoff, BO_IN_MEMORY|BO_MUST_BE_TWO_SIDED, NULL);
        g_free(gnubg_bearoff);

        /* hyper-gammon databases */

        for (i = 0; i < 3; ++i) {
            char *fn;
            char sz[10];
            sprintf(sz, "hyper%1d.bd", i + 1);
            fn = BuildFilename(sz);
            apbcHyper[i] = BearoffInit(fn, BO_IN_MEMORY, NULL);
            g_free(fn);
        }

    }

    if (szWeightsBinary) {
        pfWeights = gnubg_g_fopen(szWeightsBinary, "rb");
        if (!binary_weights_failed(szWeightsBinary, pfWeights)) {
            if (!fReadWeights && !(fReadWeights =
                                   !NeuralNetLoadBinary(&nnContact, pfWeights) &&
                                   !NeuralNetLoadBinary(&nnRace, pfWeights) &&
                                   !NeuralNetLoadBinary(&nnCrashed, pfWeights) &&
                                   !NeuralNetLoadBinary(&nnpContact, pfWeights) &&
                                   !NeuralNetLoadBinary(&nnpCrashed, pfWeights) &&
                                   !NeuralNetLoadBinary(&nnpRace, pfWeights))) {
                perror(szWeightsBinary);
            }
        }
        if (pfWeights)
            fclose(pfWeights);
        pfWeights = NULL;
    }

    if (!fReadWeights && szWeights) {
        pfWeights = gnubg_g_fopen(szWeights, "r");
        if (!weights_failed(szWeights, pfWeights)) {
            setlocale(LC_ALL, "C");
            if (!(fReadWeights =
                  !NeuralNetLoad(&nnContact, pfWeights) &&
                  !NeuralNetLoad(&nnRace, pfWeights) &&
                  !NeuralNetLoad(&nnCrashed, pfWeights) &&
                  !NeuralNetLoad(&nnpContact, pfWeights) &&
                  !NeuralNetLoad(&nnpCrashed, pfWeights) &&
                  !NeuralNetLoad(&nnpRace, pfWeights)
                ))
                perror(szWeights);
            setlocale(LC_ALL, "");
        }
        if (pfWeights)
            fclose(pfWeights);
        pfWeights = NULL;
    }

    g_assert(fReadWeights);

    g_assert(nnContact.cInput == NUM_INPUTS && nnContact.cOutput == NUM_OUTPUTS);
    g_assert(nnCrashed.cInput == NUM_INPUTS && nnCrashed.cOutput == NUM_OUTPUTS);
    g_assert(nnRace.cInput == NUM_RACE_INPUTS && nnRace.cOutput == NUM_OUTPUTS);

    g_assert(nnpContact.cInput == NUM_PRUNING_INPUTS && nnpContact.cOutput == NUM_OUTPUTS);
    g_assert(nnpCrashed.cInput == NUM_PRUNING_INPUTS && nnpCrashed.cOutput == NUM_OUTPUTS);
    g_assert(nnpRace.cInput == NUM_PRUNING_INPUTS && nnpRace.cOutput == NUM_OUTPUTS);

    if (!fReadWeights) {
        outputerrf(_("GNU Backgammon couldn't find a weights file."));
        exit(EXIT_FAILURE);
    }

}

/* Calculates inputs for any contact position, for one player only. */

static void
CalculateHalfInputs(const unsigned int anBoard[25], const unsigned int anBoardOpp[25], float afInput[])
{
    int i, j, k, l, nOppBack, n, aHit[39], nBoard;

    /* aanCombination[n] -
     * How many ways to hit from a distance of n pips.
     * Each number is an index into aIntermediate below. 
     */
    static const int aanCombination[24][5] = {
        {0, -1, -1, -1, -1},    /*  1 */
        {1, 2, -1, -1, -1},     /*  2 */
        {3, 4, 5, -1, -1},      /*  3 */
        {6, 7, 8, 9, -1},       /*  4 */
        {10, 11, 12, -1, -1},   /*  5 */
        {13, 14, 15, 16, 17},   /*  6 */
        {18, 19, 20, -1, -1},   /*  7 */
        {21, 22, 23, 24, -1},   /*  8 */
        {25, 26, 27, -1, -1},   /*  9 */
        {28, 29, -1, -1, -1},   /* 10 */
        {30, -1, -1, -1, -1},   /* 11 */
        {31, 32, 33, -1, -1},   /* 12 */
        {-1, -1, -1, -1, -1},   /* 13 */
        {-1, -1, -1, -1, -1},   /* 14 */
        {34, -1, -1, -1, -1},   /* 15 */
        {35, -1, -1, -1, -1},   /* 16 */
        {-1, -1, -1, -1, -1},   /* 17 */
        {36, -1, -1, -1, -1},   /* 18 */
        {-1, -1, -1, -1, -1},   /* 19 */
        {37, -1, -1, -1, -1},   /* 20 */
        {-1, -1, -1, -1, -1},   /* 21 */
        {-1, -1, -1, -1, -1},   /* 22 */
        {-1, -1, -1, -1, -1},   /* 23 */
        {38, -1, -1, -1, -1}    /* 24 */
    };

    /* One way to hit */
    typedef struct _Inter {
        /* if true, all intermediate points (if any) are required;
         * if false, one of two intermediate points are required.
         * Set to true for a direct hit, but that can be checked with
         * nFaces == 1,
         */
        int fAll;

        /* Intermediate points required */
        int anIntermediate[3];

        /* Number of faces used in hit (1 to 4) */
        int nFaces;

        /* Number of pips used to hit */
        int nPips;
    } Inter;

    const Inter *pi;
    /* All ways to hit */
    static const Inter aIntermediate[39] = {
        {1, {0, 0, 0}, 1, 1},   /*  0: 1x hits 1 */
        {1, {0, 0, 0}, 1, 2},   /*  1: 2x hits 2 */
        {1, {1, 0, 0}, 2, 2},   /*  2: 11 hits 2 */
        {1, {0, 0, 0}, 1, 3},   /*  3: 3x hits 3 */
        {0, {1, 2, 0}, 2, 3},   /*  4: 21 hits 3 */
        {1, {1, 2, 0}, 3, 3},   /*  5: 11 hits 3 */
        {1, {0, 0, 0}, 1, 4},   /*  6: 4x hits 4 */
        {0, {1, 3, 0}, 2, 4},   /*  7: 31 hits 4 */
        {1, {2, 0, 0}, 2, 4},   /*  8: 22 hits 4 */
        {1, {1, 2, 3}, 4, 4},   /*  9: 11 hits 4 */
        {1, {0, 0, 0}, 1, 5},   /* 10: 5x hits 5 */
        {0, {1, 4, 0}, 2, 5},   /* 11: 41 hits 5 */
        {0, {2, 3, 0}, 2, 5},   /* 12: 32 hits 5 */
        {1, {0, 0, 0}, 1, 6},   /* 13: 6x hits 6 */
        {0, {1, 5, 0}, 2, 6},   /* 14: 51 hits 6 */
        {0, {2, 4, 0}, 2, 6},   /* 15: 42 hits 6 */
        {1, {3, 0, 0}, 2, 6},   /* 16: 33 hits 6 */
        {1, {2, 4, 0}, 3, 6},   /* 17: 22 hits 6 */
        {0, {1, 6, 0}, 2, 7},   /* 18: 61 hits 7 */
        {0, {2, 5, 0}, 2, 7},   /* 19: 52 hits 7 */
        {0, {3, 4, 0}, 2, 7},   /* 20: 43 hits 7 */
        {0, {2, 6, 0}, 2, 8},   /* 21: 62 hits 8 */
        {0, {3, 5, 0}, 2, 8},   /* 22: 53 hits 8 */
        {1, {4, 0, 0}, 2, 8},   /* 23: 44 hits 8 */
        {1, {2, 4, 6}, 4, 8},   /* 24: 22 hits 8 */
        {0, {3, 6, 0}, 2, 9},   /* 25: 63 hits 9 */
        {0, {4, 5, 0}, 2, 9},   /* 26: 54 hits 9 */
        {1, {3, 6, 0}, 3, 9},   /* 27: 33 hits 9 */
        {0, {4, 6, 0}, 2, 10},  /* 28: 64 hits 10 */
        {1, {5, 0, 0}, 2, 10},  /* 29: 55 hits 10 */
        {0, {5, 6, 0}, 2, 11},  /* 30: 65 hits 11 */
        {1, {6, 0, 0}, 2, 12},  /* 31: 66 hits 12 */
        {1, {4, 8, 0}, 3, 12},  /* 32: 44 hits 12 */
        {1, {3, 6, 9}, 4, 12},  /* 33: 33 hits 12 */
        {1, {5, 10, 0}, 3, 15}, /* 34: 55 hits 15 */
        {1, {4, 8, 12}, 4, 16}, /* 35: 44 hits 16 */
        {1, {6, 12, 0}, 3, 18}, /* 36: 66 hits 18 */
        {1, {5, 10, 15}, 4, 20},        /* 37: 55 hits 20 */
        {1, {6, 12, 18}, 4, 24} /* 38: 66 hits 24 */
    };

    /* aaRoll[n] - All ways to hit with the n'th roll
     * Each entry is an index into aIntermediate above.
     */

    static const int aaRoll[21][4] = {
        {0, 2, 5, 9},           /* 11 */
        {1, 8, 17, 24},         /* 22 */
        {3, 16, 27, 33},        /* 33 */
        {6, 23, 32, 35},        /* 44 */
        {10, 29, 34, 37},       /* 55 */
        {13, 31, 36, 38},       /* 66 */
        {0, 1, 4, -1},          /* 21 */
        {0, 3, 7, -1},          /* 31 */
        {1, 3, 12, -1},         /* 32 */
        {0, 6, 11, -1},         /* 41 */
        {1, 6, 15, -1},         /* 42 */
        {3, 6, 20, -1},         /* 43 */
        {0, 10, 14, -1},        /* 51 */
        {1, 10, 19, -1},        /* 52 */
        {3, 10, 22, -1},        /* 53 */
        {6, 10, 26, -1},        /* 54 */
        {0, 13, 18, -1},        /* 61 */
        {1, 13, 21, -1},        /* 62 */
        {3, 13, 25, -1},        /* 63 */
        {6, 13, 28, -1},        /* 64 */
        {10, 13, 30, -1}        /* 65 */
    };

    /* One roll stat */

    struct {
        /* number of chequers this roll hits */
        int nChequers;

        /* count of pips this roll hits */
        int nPips;
    } aRoll[21];

    {
        int n = 0;

        for (nOppBack = 24; nOppBack >= 0; --nOppBack) {
            if (anBoardOpp[nOppBack]) {
                break;
            }
        }

        nOppBack = 23 - nOppBack;

        for (i = nOppBack + 1; i < 25; i++)
            if (anBoard[i])
                n += (i + 1 - nOppBack) * anBoard[i];

        g_assert(n);

        afInput[I_BREAK_CONTACT] = n / (15 + 152.0f);
    }
    {
        unsigned int p = 0;

        for (i = 0; i < nOppBack; i++) {
            if (anBoard[i])
                p += (i + 1) * anBoard[i];
        }

        afInput[I_FREEPIP] = p / 100.0f;
    }

    {
        int t = 0;
        int no = 0;

        int m = (nOppBack >= 11) ? nOppBack : 11;

        t += 24 * anBoard[24];
        no += anBoard[24];

        for (i = 23; i > m; --i) {
            if (anBoard[i] && anBoard[i] != 2) {
                int n = ((anBoard[i] > 2) ? (anBoard[i] - 2) : 1);
                no += n;
                t += i * n;
            }
        }

        for (; i >= 6; --i) {
            if (anBoard[i]) {
                int n = anBoard[i];
                no += n;
                t += i * n;
            }
        }

        for (i = 5; i >= 0; --i) {
            if (anBoard[i] > 2) {
                t += i * (anBoard[i] - 2);
                no += (anBoard[i] - 2);
            } else if (anBoard[i] < 2) {
                int n = (2 - anBoard[i]);

                if (no >= n) {
                    t -= i * n;
                    no -= n;
                }
            }
        }

        afInput[I_TIMING] = t / 100.0f;
    }

    /* Back chequer */

    {
        int nBack;

        for (nBack = 24; nBack >= 0; --nBack) {
            if (anBoard[nBack]) {
                break;
            }
        }

        afInput[I_BACK_CHEQUER] = nBack / 24.0f;

        /* Back anchor */

        for (i = ((nBack == 24) ? 23 : nBack); i >= 0; --i) {
            if (anBoard[i] >= 2) {
                break;
            }
        }

        afInput[I_BACK_ANCHOR] = i / 24.0f;

        /* Forward anchor */

        n = 0;
        for (j = 18; j <= i; ++j) {
            if (anBoard[j] >= 2) {
                n = 24 - j;
                break;
            }
        }

        if (n == 0) {
            for (j = 17; j >= 12; --j) {
                if (anBoard[j] >= 2) {
                    n = 24 - j;
                    break;
                }
            }
        }

        afInput[I_FORWARD_ANCHOR] = n == 0 ? 2.0f : n / 6.0f;
    }


    /* Piploss */

    nBoard = 0;
    for (i = 0; i < 6; i++)
        if (anBoard[i])
            nBoard++;

    memset(aHit, 0, sizeof(aHit));

    /* for every point we'd consider hitting a blot on, */

    for (i = (nBoard > 2) ? 23 : 21; i >= 0; i--)
        /* if there's a blot there, then */

        if (anBoardOpp[i] == 1)
            /* for every point beyond */

            for (j = 24 - i; j < 25; j++)
                /* if we have a hitter and are willing to hit */

                if (anBoard[j] && !(j < 6 && anBoard[j] == 2))
                    /* for every roll that can hit from that point */

                    for (n = 0; n < 5; n++) {
                        if (aanCombination[j - 24 + i][n] == -1)
                            break;

                        /* find the intermediate points required to play */

                        pi = aIntermediate + aanCombination[j - 24 + i][n];

                        if (pi->fAll) {
                            /* if nFaces is 1, there are no intermediate points */

                            if (pi->nFaces > 1) {
                                /* all the intermediate points are required */

                                for (k = 0; k < 3 && pi->anIntermediate[k] > 0; k++)
                                    if (anBoardOpp[i - pi->anIntermediate[k]] > 1)
                                        /* point is blocked; look for other hits */
                                        goto cannot_hit;
                            }
                        } else {
                            /* either of two points are required */

                            if (anBoardOpp[i - pi->anIntermediate[0]] > 1 && anBoardOpp[i - pi->anIntermediate[1]] > 1) {
                                /* both are blocked; look for other hits */
                                goto cannot_hit;
                            }
                        }

                        /* enter this shot as available */

                        aHit[aanCombination[j - 24 + i][n]] |= 1 << j;
                      cannot_hit:;
                    }

    memset(aRoll, 0, sizeof(aRoll));

    if (!anBoard[24]) {
        /* we're not on the bar; for each roll, */

        for (i = 0; i < 21; i++) {
            n = -1;             /* (hitter used) */

            /* for each way that roll hits, */
            for (j = 0; j < 4; j++) {
                int r = aaRoll[i][j];

                if (r < 0)
                    break;

                if (!aHit[r])
                    continue;

                pi = aIntermediate + r;

                if (pi->nFaces == 1) {
                    /* direct shot */
                    k = msb32(aHit[r]);
                    /* select the most advanced blot; if we still have
                     * a chequer that can hit there */

                    if (n != k || anBoard[k] > 1)
                        aRoll[i].nChequers++;

                    n = k;

                    if (k - pi->nPips + 1 > aRoll[i].nPips)
                        aRoll[i].nPips = k - pi->nPips + 1;

                    /* if rolling doubles, check for multiple
                     * direct shots */

                    if (aaRoll[i][3] >= 0 && aHit[r] & ~(1 << k))
                        aRoll[i].nChequers++;

                } else {
                    /* indirect shot */
                    if (!aRoll[i].nChequers)
                        aRoll[i].nChequers = 1;

                    /* find the most advanced hitter */

                    k = msb32(aHit[r]);

                    if (k - pi->nPips + 1 > aRoll[i].nPips)
                        aRoll[i].nPips = k - pi->nPips + 1;

                    /* check for blots hit on intermediate points */

                    for (l = 0; l < 3 && pi->anIntermediate[l] > 0; l++)
                        if (anBoardOpp[23 - k + pi->anIntermediate[l]] == 1) {

                            aRoll[i].nChequers++;
                            break;
                        }
                }
            }
        }
    } else if (anBoard[24] == 1) {
        /* we have one on the bar; for each roll, */

        for (i = 0; i < 21; i++) {
            n = 0;              /* (free to use either die to enter) */

            for (j = 0; j < 4; j++) {
                int r = aaRoll[i][j];

                if (r < 0)
                    break;

                if (!aHit[r])
                    continue;

                pi = aIntermediate + r;

                if (pi->nFaces == 1) {
                    /* direct shot */

                    /* FIXME: There must be a more profitable way to use
                     * the possibility of finding the msb quickly,
                     * but I don't understand the code below. */
#ifdef HAVE___BUILTIN_CLZ
                    /* This shortcut is worthwhile only if msb32 is fast */
                    for (k = msb32(aHit[r]); k > 0; k--) {
#else
                    for (k = 24; k > 0; k--) {
#endif
                        if (aHit[r] & (1 << k)) {
                            /* if we need this die to enter, we can't hit elsewhere */

                            if (n && k != 24)
                                break;

                            /* if this isn't a shot from the bar, the
                             * other die must be used to enter */

                            if (k != 24) {
                                int npip = aIntermediate[aaRoll[i][1 - j]].nPips;

                                if (anBoardOpp[npip - 1] > 1)
                                    break;

                                n = 1;
                            }

                            aRoll[i].nChequers++;

                            if (k - pi->nPips + 1 > aRoll[i].nPips)
                                aRoll[i].nPips = k - pi->nPips + 1;
                        }
                    }
                } else {
                    /* indirect shot -- consider from the bar only */
                    if (!(aHit[r] & (1 << 24)))
                        continue;

                    if (!aRoll[i].nChequers)
                        aRoll[i].nChequers = 1;

                    if (25 - pi->nPips > aRoll[i].nPips)
                        aRoll[i].nPips = 25 - pi->nPips;

                    /* check for blots hit on intermediate points */
                    for (k = 0; k < 3 && pi->anIntermediate[k] > 0; k++)
                        if (anBoardOpp[pi->anIntermediate[k] + 1] == 1) {

                            aRoll[i].nChequers++;
                            break;
                        }
                }
            }
        }
    } else {
        /* we have more than one on the bar --
         * count only direct shots from point 24 */

        for (i = 0; i < 21; i++) {
            /* for the first two ways that hit from the bar */

            for (j = 0; j < 2; j++) {
                int r = aaRoll[i][j];

                if (!(aHit[r] & (1 << 24)))
                    continue;

                pi = aIntermediate + r;

                /* only consider direct shots */

                if (pi->nFaces != 1)
                    continue;

                aRoll[i].nChequers++;

                if (25 - pi->nPips > aRoll[i].nPips)
                    aRoll[i].nPips = 25 - pi->nPips;
            }
        }
    }

    {
        int np = 0;
        int n1 = 0;
        int n2 = 0;

        for (i = 0; i < 6; i++) {
            int nc = aRoll[i].nChequers;

            np += aRoll[i].nPips;

            if (nc > 0) {
                n1 += 1;

                if (nc > 1) {
                    n2 += 1;
                }
            }
        }

        for (; i < 21; i++) {
            int nc = aRoll[i].nChequers;

            np += aRoll[i].nPips * 2;

            if (nc > 0) {
                n1 += 2;

                if (nc > 1) {
                    n2 += 2;
                }
            }
        }

        afInput[I_PIPLOSS] = np / (12.0f * 36.0f);

        afInput[I_P1] = n1 / 36.0f;
        afInput[I_P2] = n2 / 36.0f;
    }

    afInput[I_BACKESCAPES] = Escapes(anBoard, 23 - nOppBack) / 36.0f;

    afInput[I_BACKRESCAPES] = Escapes1(anBoard, 23 - nOppBack) / 36.0f;

    for (n = 36, i = 15; i < 24 - nOppBack; i++)
        if ((j = Escapes(anBoard, i)) < n)
            n = j;

    afInput[I_ACONTAIN] = (36 - n) / 36.0f;
    afInput[I_ACONTAIN2] = afInput[I_ACONTAIN] * afInput[I_ACONTAIN];

    if (nOppBack < 0) {
        /* restart loop, point 24 should not be included */
        i = 15;
        n = 36;
    }

    for (; i < 24; i++)
        if ((j = Escapes(anBoard, i)) < n)
            n = j;


    afInput[I_CONTAIN] = (36 - n) / 36.0f;
    afInput[I_CONTAIN2] = afInput[I_CONTAIN] * afInput[I_CONTAIN];

    for (n = 0, i = 6; i < 25; i++)
        if (anBoard[i])
            n += (i - 5) * anBoard[i] * Escapes(anBoardOpp, i);

    afInput[I_MOBILITY] = n / 3600.0f;

    j = 0;
    n = 0;
    for (i = 0; i < 25; i++) {
        int ni = anBoard[i];

        if (ni) {
            j += ni;
            n += i * ni;
        }
    }

    if (j) {
        n = (n + j - 1) / j;
    }

    j = 0;
    for (k = 0, i = n + 1; i < 25; i++) {
        int ni = anBoard[i];

        if (ni) {
            j += ni;
            k += ni * (i - n) * (i - n);
        }
    }

    if (j) {
        k = (k + j - 1) / j;
    }

    afInput[I_MOMENT2] = k / 400.0f;

    if (anBoard[24] > 0) {
        int loss = 0;
        int two = anBoard[24] > 1;

        for (i = 0; i < 6; ++i) {
            if (anBoardOpp[i] > 1) {
                /* any double loses */

                loss += 4 * (i + 1);

                for (j = i + 1; j < 6; ++j) {
                    if (anBoardOpp[j] > 1) {
                        loss += 2 * (i + j + 2);
                    } else {
                        if (two) {
                            loss += 2 * (i + 1);
                        }
                    }
                }
            } else {
                if (two) {
                    for (j = i + 1; j < 6; ++j) {
                        if (anBoardOpp[j] > 1) {
                            loss += 2 * (j + 1);
                        }
                    }
                }
            }
        }

        afInput[I_ENTER] = loss / (36.0f * (49.0f / 6.0f));
    } else {
        afInput[I_ENTER] = 0.0f;
    }

    n = 0;
    for (i = 0; i < 6; i++) {
        n += anBoardOpp[i] > 1;
    }

    afInput[I_ENTER2] = (36 - (n - 6) * (n - 6)) / 36.0f;

    {
        int pa = -1;
        int w = 0;
        int tot = 0;
        int np;

        for (np = 23; np > 0; --np) {
            if (anBoard[np] >= 2) {
                if (pa == -1) {
                    pa = np;
                    continue;
                }

                {
                    int d = pa - np;

                    static int ac[23] = { 11, 11, 11, 11, 11, 11, 11,
                        6, 5, 4, 3, 2,
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    };

                    w += ac[d] * anBoard[pa];
                    tot += anBoard[pa];
                }
            }
        }

        if (tot) {
            afInput[I_BACKBONE] = 1 - (w / (tot * 11.0f));
        } else {
            afInput[I_BACKBONE] = 0;
        }
    }

    {
        unsigned int nAc = 0;

        for (i = 18; i < 24; ++i) {
            if (anBoard[i] > 1) {
                ++nAc;
            }
        }

        afInput[I_BACKG] = 0.0;
        afInput[I_BACKG1] = 0.0;

        if (nAc >= 1) {
            unsigned int tot = 0;
            for (i = 18; i < 25; ++i) {
                tot += anBoard[i];
            }

            if (nAc > 1) {
                /* g_assert( tot >= 4 ); */

                afInput[I_BACKG] = (tot - 3) / 4.0f;
            } else if (nAc == 1) {
                afInput[I_BACKG1] = tot / 8.0f;
            }
        }
    }
}


static void
CalculateRaceInputs(const TanBoard anBoard, float inputs[])
{
    unsigned int side;

    for (side = 0; side < 2; ++side) {
        unsigned int i, k;

        const unsigned int *const board = anBoard[side];
        float *const afInput = inputs + side * HALF_RACE_INPUTS;

        unsigned int menOff = 15;

        {
            g_assert(board[23] == 0 && board[24] == 0);
        }

        /* Points */
        for (i = 0; i < 23; ++i) {
            unsigned int const nc = board[i];

            k = i * 4;

            menOff -= nc;

            afInput[k++] = (nc == 1) ? 1.0f : 0.0f;
            afInput[k++] = (nc == 2) ? 1.0f : 0.0f;
            afInput[k++] = (nc >= 3) ? 1.0f : 0.0f;
            afInput[k] = nc > 3 ? (nc - 3) / 2.0f : 0.0f;
        }

        /* Men off */
        for (k = 0; k < 14; ++k) {
            afInput[RI_OFF + k] = (menOff == (k + 1)) ? 1.0f : 0.0f;
        }

        {
            unsigned int nCross = 0;

            for (k = 1; k < 4; ++k) {
                for (i = 6 * k; i < 6 * k + 6; ++i) {
                    unsigned int const nc = board[i];

                    if (nc) {
                        nCross += nc * k;
                    }
                }
            }

            afInput[RI_NCROSS] = nCross / 10.0f;
        }
    }
}

/* baseInputs() is now in lib/inputs.c */

static void
menOffAll(const unsigned int *anBoard, float *afInput)
{
    /* Men off */
    int menOff = 15;
    int i;

    for (i = 0; i < 25; i++) {
        menOff -= anBoard[i];
    }

    if (menOff <= 5) {
        afInput[0] = menOff ? menOff / 5.0f : 0.0f;
        afInput[1] = 0.0f;
        afInput[2] = 0.0f;
    } else if (menOff <= 10) {
        afInput[0] = 1.0f;
        afInput[1] = (menOff - 5) / 5.0f;
        afInput[2] = 0.0f;
    } else {
        afInput[0] = 1.0;
        afInput[1] = 1.0;
        afInput[2] = (menOff - 10) / 5.0f;
    }
}

static void
menOffNonCrashed(const unsigned int *anBoard, float *afInput)
{
    int menOff = 15;
    int i;

    for (i = 0; i < 25; ++i) {
        menOff -= anBoard[i];
    }
    {
        g_assert(menOff <= 8);
    }

    if (menOff <= 2) {
        afInput[0] = menOff ? menOff / 3.0f : 0.0f;
        afInput[1] = 0.0f;
        afInput[2] = 0.0f;
    } else if (menOff <= 5) {
        afInput[0] = 1.0f;
        afInput[1] = (menOff - 3) / 3.0f;
        afInput[2] = 0.0f;
    } else {
        afInput[0] = 1.0f;
        afInput[1] = 1.0f;
        afInput[2] = (menOff - 6) / 3.0f;
    }

}

/* Calculates contact neural net inputs from the board position. */

static void
CalculateContactInputs(const TanBoard anBoard, float arInput[])
{
    baseInputs(anBoard, arInput);

    {
        float *b = arInput + MINPPERPOINT * 25 * 2;

        /* I accidentally switched sides (0 and 1) when I trained the net */
        menOffNonCrashed(anBoard[0], b + I_OFF1);

        CalculateHalfInputs(anBoard[1], anBoard[0], b);
    }

    {
        float *b = arInput + (MINPPERPOINT * 25 * 2 + MORE_INPUTS);

        menOffNonCrashed(anBoard[1], b + I_OFF1);

        CalculateHalfInputs(anBoard[0], anBoard[1], b);
    }
}

/* Calculates crashed neural net inputs from the board position. */

static void
CalculateCrashedInputs(const TanBoard anBoard, float arInput[])
{
    baseInputs(anBoard, arInput);

    {
        float *b = arInput + MINPPERPOINT * 25 * 2;

        menOffAll(anBoard[1], b + I_OFF1);

        CalculateHalfInputs(anBoard[1], anBoard[0], b);
    }

    {
        float *b = arInput + (MINPPERPOINT * 25 * 2 + MORE_INPUTS);

        menOffAll(anBoard[0], b + I_OFF1);

        CalculateHalfInputs(anBoard[0], anBoard[1], b);
    }
}

extern void
swap_us(unsigned int *p0, unsigned int *p1)
{
    unsigned int n = *p0;

    *p0 = *p1;
    *p1 = n;
}

extern void
swap(int *p0, int *p1)
{
    int n = *p0;

    *p0 = *p1;
    *p1 = n;
}

extern void
SwapSides(TanBoard anBoard)
{

    int i, n;

    for (i = 0; i < 25; i++) {
        n = anBoard[0][i];
        anBoard[0][i] = anBoard[1][i];
        anBoard[1][i] = n;
    }
}

/* An upper bound on the number of turns it can take to complete a bearoff
 * from bearoff position ID i. */
static int
MaxTurns(int id)
{
    unsigned short int aus[32];
    int i;

    BearoffDist(pbc1, id, NULL, NULL, NULL, aus, NULL);

    for (i = 31; i >= 0; i--) {
        if (aus[i])
            return i;
    }

    return -1;
}

extern void
SanityCheck(const TanBoard anBoard, float arOutput[])
{
    int i, j, nciq, ac[2], anBack[2], anCross[2], anGammonCross[2], anMaxTurns[2], fContact;

    g_assert(arOutput[OUTPUT_WIN] >= 0.0f && arOutput[OUTPUT_WIN] <= 1.0f);
    g_assert(arOutput[OUTPUT_WINGAMMON] >= 0.0f && arOutput[OUTPUT_WINGAMMON] <= 1.0f);
    g_assert(arOutput[OUTPUT_WINBACKGAMMON] >= 0.0f && arOutput[OUTPUT_WINBACKGAMMON] <= 1.0f);
    g_assert(arOutput[OUTPUT_LOSEGAMMON] >= 0.0f && arOutput[OUTPUT_LOSEGAMMON] <= 1.0f);
    g_assert(arOutput[OUTPUT_LOSEBACKGAMMON] >= 0.0f && arOutput[OUTPUT_LOSEBACKGAMMON] <= 1.0f);

    ac[0] = ac[1] = anBack[0] = anBack[1] = anCross[0] = anCross[1] = 0;
    anGammonCross[0] = anGammonCross[1] = 1;

    for (j = 0; j < 2; j++) {
        for (i = 0, nciq = 0; i < 6; i++)
            if (anBoard[j][i]) {
                anBack[j] = i;
                nciq += anBoard[j][i];
            }
        ac[j] = anCross[j] = nciq;

        for (i = 6, nciq = 0; i < 12; i++)
            if (anBoard[j][i]) {
                anBack[j] = i;
                nciq += anBoard[j][i];
            }
        ac[j] += nciq;
        anCross[j] += 2 * nciq;
        anGammonCross[j] += nciq;

        for (i = 12, nciq = 0; i < 18; i++)
            if (anBoard[j][i]) {
                anBack[j] = i;
                nciq += anBoard[j][i];
            }
        ac[j] += nciq;
        anCross[j] += 3 * nciq;
        anGammonCross[j] += 2 * nciq;

        for (i = 18, nciq = 0; i < 24; i++)
            if (anBoard[j][i]) {
                anBack[j] = i;
                nciq += anBoard[j][i];
            }
        ac[j] += nciq;
        anCross[j] += 4 * nciq;
        anGammonCross[j] += 3 * nciq;

        if (anBoard[j][24]) {
            anBack[j] = 24;
            ac[j] += anBoard[j][24];
            anCross[j] += 5 * anBoard[j][24];
            anGammonCross[j] += 4 * anBoard[j][24];
        }
    }

    fContact = anBack[0] + anBack[1] >= 24;

    if (unlikely(!fContact)) {
        for (i = 0; i < 2; i++)
            if (anBack[i] < 6 && pbc1)
                anMaxTurns[i] = MaxTurns(PositionBearoff(anBoard[i], pbc1->nPoints, pbc1->nChequers));
            else
                anMaxTurns[i] = anCross[i] * 2;

        if (unlikely(!anMaxTurns[1]))
            anMaxTurns[1] = 1;

    }

    if (unlikely(!fContact) && anCross[0] > 4 * (anMaxTurns[1] - 1))
        /* Certain win */
        arOutput[OUTPUT_WIN] = 1.0f;

    if (unlikely(ac[0] < 15))
        /* Opponent has borne off; no gammons or backgammons possible */
        arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WINBACKGAMMON] = 0.0f;
    else if (unlikely(!fContact)) {
        if (anCross[1] > 8 * anGammonCross[0])
            /* Gammon impossible */
            arOutput[OUTPUT_WINGAMMON] = 0.0f;
        else if (anGammonCross[0] > 4 * (anMaxTurns[1] - 1))
            /* Certain gammon */
            arOutput[OUTPUT_WINGAMMON] = 1.0f;
        if (anBack[0] < 18)
            /* Backgammon impossible */
            arOutput[OUTPUT_WINBACKGAMMON] = 0.0f;
    }

    if (unlikely(!fContact) && anCross[1] > 4 * anMaxTurns[0])
        /* Certain loss */
        arOutput[OUTPUT_WIN] = 0.0f;

    if (unlikely(ac[1] < 15))
        /* Player has borne off; no gammon or backgammon losses possible */
        arOutput[OUTPUT_LOSEGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0f;
    else if (unlikely(!fContact)) {
        if (anCross[0] > 8 * anGammonCross[1] - 4)
            /* Gammon loss impossible */
            arOutput[OUTPUT_LOSEGAMMON] = 0.0f;
        else if (anGammonCross[1] > 4 * anMaxTurns[0])
            /* Certain gammon loss */
            arOutput[OUTPUT_LOSEGAMMON] = 1.0f;
        if (anBack[1] < 18)
            /* Backgammon impossible */
            arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0f;
    }

    /* gammons must be less than wins */
    if (unlikely(arOutput[OUTPUT_WINGAMMON] > arOutput[OUTPUT_WIN])) {
        arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WIN];
    }

    {
        float lose = 1.0f - arOutput[OUTPUT_WIN];
        if (unlikely(arOutput[OUTPUT_LOSEGAMMON] > lose)) {
            arOutput[OUTPUT_LOSEGAMMON] = lose;
        }
    }

    /* Backgammons cannot exceed gammons */
    if (unlikely(arOutput[OUTPUT_WINBACKGAMMON] > arOutput[OUTPUT_WINGAMMON]))
        arOutput[OUTPUT_WINBACKGAMMON] = arOutput[OUTPUT_WINGAMMON];

    if (unlikely(arOutput[OUTPUT_LOSEBACKGAMMON] > arOutput[OUTPUT_LOSEGAMMON]))
        arOutput[OUTPUT_LOSEBACKGAMMON] = arOutput[OUTPUT_LOSEGAMMON];

    if (fContact) {
        float noise = 1 / 10000.0f;

        for (i = OUTPUT_WINGAMMON; i < NUM_OUTPUTS; ++i) {
            if (unlikely(arOutput[i] < noise)) {
                arOutput[i] = 0.0f;
            }
        }
    }

}


extern positionclass
ClassifyPosition(const TanBoard anBoard, const bgvariation bgv)
{
    int nOppBack = -1, nBack = -1;

    for (nOppBack = 24; nOppBack >= 0; --nOppBack) {
        if (anBoard[0][nOppBack]) {
            break;
        }
    }

    for (nBack = 24; nBack >= 0; --nBack) {
        if (anBoard[1][nBack]) {
            break;
        }
    }

    if (unlikely(nBack < 0 || nOppBack < 0))
        return CLASS_OVER;

    /* special classes for hypergammon variants */

    switch (bgv) {
    case VARIATION_HYPERGAMMON_1:
        return CLASS_HYPERGAMMON1;

    case VARIATION_HYPERGAMMON_2:
        return CLASS_HYPERGAMMON2;

    case VARIATION_HYPERGAMMON_3:
        return CLASS_HYPERGAMMON3;

    case VARIATION_STANDARD:
    case VARIATION_NACKGAMMON:

        /* normal backgammon */

        if (nBack + nOppBack > 22) {

            /* contact position */

            unsigned int const N = 6;
            unsigned int i;
            unsigned int side;

            for (side = 0; side < 2; ++side) {
                unsigned int tot = 0;

                const unsigned int *board = anBoard[side];

                for (i = 0; i < 25; ++i) {
                    tot += board[i];
                }

                if (unlikely(tot <= N)) {
                    return CLASS_CRASHED;
                } else {
                    if (unlikely(board[0] > 1)) {
                        if (unlikely(tot <= (N + board[0]))) {
                            return CLASS_CRASHED;
                        } else {
                            if (unlikely((1 + tot - (board[0] + board[1])) <= N) && board[1] > 1) {
                                return CLASS_CRASHED;
                            }
                        }
                    } else {
                        if (unlikely(tot <= (N + (board[1] - 1)))) {
                            return CLASS_CRASHED;
                        }
                    }
                }
            }

            return CLASS_CONTACT;
        } else {

            if (unlikely(isBearoff(pbc2, anBoard)))
                return CLASS_BEAROFF2;

            if (unlikely(isBearoff(pbcTS, anBoard)))
                return CLASS_BEAROFF_TS;

            if (unlikely(isBearoff(pbc1, anBoard)))
                return CLASS_BEAROFF1;

            if (unlikely(isBearoff(pbcOS, anBoard)))
                return CLASS_BEAROFF_OS;

            return CLASS_RACE;

        }

    default:

        g_assert_not_reached();

    }

    return CLASS_OVER;          /* for fussy compilers */
}

static int
EvalBearoff2(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{
    g_assert(pbc2);

    return BearoffEval(pbc2, anBoard, arOutput);
}

static int
EvalBearoffOS(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(pbcOS, anBoard, arOutput);

}


static int
EvalBearoffTS(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(pbcTS, anBoard, arOutput);

}

static int
EvalHypergammon1(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(apbcHyper[0], anBoard, arOutput);

}

static int
EvalHypergammon2(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(apbcHyper[1], anBoard, arOutput);

}

static int
EvalHypergammon3(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(apbcHyper[2], anBoard, arOutput);

}

static int
EvalBearoff1(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * UNUSED(nnStates))
{

    return BearoffEval(pbc1, anBoard, arOutput);

}

enum {
    /* gammon possible by side on roll */
    G_POSSIBLE = 0x1,
    /* backgammon possible by side on roll */
    BG_POSSIBLE = 0x2,
    /* gammon possible by side not on roll */
    OG_POSSIBLE = 0x4,
    /* backgammon possible by side not on roll */
    OBG_POSSIBLE = 0x8
};

/* side - side that potentially can win a backgammon */
/* Return - Probablity that side will win a backgammon */

static float
raceBGprob(const TanBoard anBoard, int side, const bgvariation bgv)
{
    int totMenHome = 0;
    int totPipsOp = 0;
    unsigned int i;
    TanBoard dummy;

    for (i = 0; i < 6; ++i) {
        totMenHome += anBoard[side][i];
    }

    for (i = 22; i >= 18; --i) {
        totPipsOp += anBoard[1 - side][i] * (i - 17);
    }

    if (!((totMenHome + 3) / 4 - (side == 1 ? 1 : 0) <= (totPipsOp + 2) / 3)) {
        return 0.0;
    }

    for (i = 0; i < 25; ++i) {
        dummy[side][i] = anBoard[side][i];
    }

    for (i = 0; i < 6; ++i) {
        dummy[1 - side][i] = anBoard[1 - side][18 + i];
    }

    for (i = 6; i < 25; ++i) {
        dummy[1 - side][i] = 0;
    }

    {
        float p = 0.0f;
        const long *bgp = getRaceBGprobs(dummy[1 - side]);
        if (bgp) {
            int k = PositionBearoff(anBoard[side], pbc1->nPoints, pbc1->nChequers);
            unsigned short int aProb[32];

            unsigned int j;

            unsigned long scale = (side == 0) ? 36 : 1;

            BearoffDist(pbc1, k, NULL, NULL, NULL, aProb, NULL);

            for (j = 1 - side; j < RBG_NPROBS; j++) {
                unsigned long sum = 0;
                scale *= 36;
                for (i = 1; i <= j + side; ++i) {
                    sum += aProb[i];
                }
                p += ((float) bgp[j]) / scale * sum;
            }

            p /= 65535.0f;

        } else {
            float ap[5];

            if (PositionBearoff(dummy[0], 6, 15) > 923 || PositionBearoff(dummy[1], 6, 15) > 923) {
                EvalBearoff1((ConstTanBoard) dummy, ap, bgv, NULL);
            } else {
                EvalBearoff2((ConstTanBoard) dummy, ap, bgv, NULL);
            }

            p = (side == 1 ? ap[0] : 1 - ap[0]);
        }

        return MIN(p, 1.0f);
    }
}

extern void
EvalRaceBG(const TanBoard anBoard, float arOutput[], const bgvariation bgv)

/* anBoard[1] is on roll */
{
    /* total men for side not on roll */
    int totMen0 = 0;

    /* total men for side on roll */
    int totMen1 = 0;

    /* a set flag for every possible outcome */
    int any = 0;

    int i;

    for (i = 23; i >= 0; --i) {
        totMen0 += anBoard[0][i];
        totMen1 += anBoard[1][i];
    }

    if (totMen1 == 15) {
        any |= OG_POSSIBLE;
    }

    if (totMen0 == 15) {
        any |= G_POSSIBLE;
    }

    if (any) {
        if (any & OG_POSSIBLE) {
            for (i = 23; i >= 18; --i) {
                if (anBoard[1][i] > 0) {
                    break;
                }
            }
            if (i >= 18) {
                any |= OBG_POSSIBLE;
            }
        }

        if (any & G_POSSIBLE) {
            for (i = 23; i >= 18; --i) {
                if (anBoard[0][i] > 0) {
                    break;
                }
            }

            if (i >= 18) {
                any |= BG_POSSIBLE;
            }
        }
    }

    if (any & (BG_POSSIBLE | OBG_POSSIBLE)) {
        /* side that can have the backgammon */
        int side = (any & BG_POSSIBLE) ? 1 : 0;

        float pr = raceBGprob(anBoard, side, bgv);

        if (pr > 0.0f) {
            if (side == 1) {
                arOutput[OUTPUT_WINBACKGAMMON] = pr;

                if (arOutput[OUTPUT_WINGAMMON] < arOutput[OUTPUT_WINBACKGAMMON]) {
                    arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WINBACKGAMMON];
                }
            } else {
                arOutput[OUTPUT_LOSEBACKGAMMON] = pr;

                if (arOutput[OUTPUT_LOSEGAMMON] < arOutput[OUTPUT_LOSEBACKGAMMON]) {
                    arOutput[OUTPUT_LOSEGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON];
                }
            }
        } else {
            if (side == 1) {
                arOutput[OUTPUT_WINBACKGAMMON] = 0.0;
            } else {
                arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0;
            }
        }
    }
}

static int
EvalRace(const TanBoard anBoard, float arOutput[], const bgvariation bgv, NNState * nnStates)
{
    SSE_ALIGN(float arInput[NUM_RACE_INPUTS]);

    CalculateRaceInputs(anBoard, arInput);

#if defined(USE_SIMD_INSTRUCTIONS)
    if (NeuralNetEvaluateSSE(&nnRace, arInput, arOutput, nnStates ? nnStates + (CLASS_RACE - CLASS_RACE) : NULL))
#else
    if (NeuralNetEvaluate(&nnRace, arInput, arOutput, nnStates ? nnStates + (CLASS_RACE - CLASS_RACE) : NULL))
#endif
        return -1;

    /* special evaluation of backgammons overrides net output */

    EvalRaceBG(anBoard, arOutput, bgv);

    /* sanity check will take care of rest */

    return 0;
}

static int
EvalContact(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * nnStates)
{
    SSE_ALIGN(float arInput[NUM_INPUTS]);

    CalculateContactInputs(anBoard, arInput);

#if defined(USE_SIMD_INSTRUCTIONS)
    return NeuralNetEvaluateSSE(&nnContact, arInput, arOutput,
                                nnStates ? nnStates + (CLASS_CONTACT - CLASS_RACE) : NULL);
#else
    return NeuralNetEvaluate(&nnContact, arInput, arOutput, nnStates ? nnStates + (CLASS_CONTACT - CLASS_RACE) : NULL);
#endif
}

static int
EvalCrashed(const TanBoard anBoard, float arOutput[], const bgvariation UNUSED(bgv), NNState * nnStates)
{
    SSE_ALIGN(float arInput[NUM_INPUTS]);

    CalculateCrashedInputs(anBoard, arInput);

#if defined(USE_SIMD_INSTRUCTIONS)
    return NeuralNetEvaluateSSE(&nnCrashed, arInput, arOutput,
                                nnStates ? nnStates + (CLASS_CRASHED - CLASS_RACE) : NULL);
#else
    return NeuralNetEvaluate(&nnCrashed, arInput, arOutput, nnStates ? nnStates + (CLASS_CRASHED - CLASS_RACE) : NULL);
#endif
}

extern int
EvalOver(const TanBoard anBoard, float arOutput[], const bgvariation bgv, NNState * UNUSED(nnStates))
{
    int i, c;
    int n = anChequers[bgv];

    for (i = 0; i < 25; i++)
        if (anBoard[0][i])
            break;

    if (i == 25) {
        /* opponent has no pieces on board; player has lost */
        arOutput[OUTPUT_WIN] = arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WINBACKGAMMON] = 0.0;

        for (i = 0, c = 0; i < 25; i++)
            c += anBoard[1][i];

        if (c == n) {
            /* player still has all pieces on board; loses gammon */
            arOutput[OUTPUT_LOSEGAMMON] = 1.0;

            for (i = 18; i < 25; i++)
                if (anBoard[1][i]) {
                    /* player still has pieces in opponent's home board;
                     * loses backgammon */
                    arOutput[OUTPUT_LOSEBACKGAMMON] = 1.0;

                    return 0;
                }

            arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0;

            return 0;
        }

        arOutput[OUTPUT_LOSEGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0;

        return 0;
    }

    for (i = 0; i < 25; i++)
        if (anBoard[1][i])
            break;

    if (i == 25) {
        /* player has no pieces on board; wins */
        arOutput[OUTPUT_WIN] = 1.0;
        arOutput[OUTPUT_LOSEGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0;

        for (i = 0, c = 0; i < 25; i++)
            c += anBoard[0][i];

        if (c == n) {
            /* opponent still has all pieces on board; win gammon */
            arOutput[OUTPUT_WINGAMMON] = 1.0;

            for (i = 18; i < 25; i++)
                if (anBoard[0][i]) {
                    /* opponent still has pieces in player's home board;
                     * win backgammon */
                    arOutput[OUTPUT_WINBACKGAMMON] = 1.0;

                    return 0;
                }

            arOutput[OUTPUT_WINBACKGAMMON] = 0.0;

            return 0;
        }

        arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WINBACKGAMMON] = 0.0;
    }

    return 0;

}

classevalfunc acef[N_CLASSES] = {
    EvalOver,
    EvalHypergammon1,
    EvalHypergammon2,
    EvalHypergammon3,
    EvalBearoff2, EvalBearoffTS,
    EvalBearoff1, EvalBearoffOS,
    EvalRace, EvalCrashed, EvalContact
};

extern float
Noise(const evalcontext * pec, const TanBoard anBoard, int iOutput)
{
    float r;

    if (pec->fDeterministic) {
        char auchBoard[50], auch[16];
        int i;

        for (i = 0; i < 25; i++) {
            auchBoard[i << 1] = (char) anBoard[0][i];
            auchBoard[(i << 1) + 1] = (char) anBoard[1][i];
        }

        auchBoard[0] += iOutput;

        md5_buffer(auchBoard, 50, auch);

        /* We can't use a Box-Muller transform here, because generating
         * a point in the unit circle requires a potentially unbounded
         * number of integers, and all we have is the board.  So we
         * just take the sum of the bytes in the hash, which (by the
         * central limit theorem) should have a normal-ish distribution. */

        r = 0.0f;
        for (i = 0; i < 16; i++)
            r += auch[i];

        r -= 2040.0f;
        r /= 295.6f;
    } else {
        /* Box-Muller transform of a point in the unit circle. */
        float x, y;

        do {
            x = (float) irand(&rc) * 2.0f / UB4MAXVAL - 1.0f;
            y = (float) irand(&rc) * 2.0f / UB4MAXVAL - 1.0f;
            r = x * x + y * y;
        } while (r > 1.0f || r == 0.0f);

        r = y * sqrtf(-2.0f * logf(r) / r);
    }

    r *= pec->rNoise;

    if (iOutput == OUTPUT_WINGAMMON || iOutput == OUTPUT_LOSEGAMMON)
        r *= 0.25f;
    else if (iOutput == OUTPUT_WINBACKGAMMON || iOutput == OUTPUT_LOSEBACKGAMMON)
        r *= 0.01f;

    return r;
}

extern int
EvalKey(const evalcontext * pec, const int nPlies, const cubeinfo * pci, int fCubefulEquity)
{

    int iKey;
    /*
     * Bit 00-03: nPlies
     * Bit 04   : fCubeful
     * Bit 05   : fMove
     * Bit 06   : fUsePrune
     * Bit 07-12: anScore[ 0 ]
     * Bit 13-18: anScore[ 1 ]
     * Bit 19-22: log2(nCube)
     * Bit 23-24: fCubeOwner
     * Bit 25   : fCrawford
     * Bit 26   : fJacoby
     * Bit 27   : fBeavers
     */

    iKey = (nPlies | (pec->fCubeful << 4) | (pci->fMove << 5));

    if (nPlies)
        iKey ^= ((pec->fUsePrune) << 6);


    if (nPlies || fCubefulEquity) {
        /* In match play, the score and cube value and position are important. */
        if (pci->nMatchTo)
            iKey ^=
                ((pci->nMatchTo - pci->anScore[pci->fMove] - 1) << 7) ^
                ((pci->nMatchTo - pci->anScore[!pci->fMove] - 1) << 13) ^
                (LogCube(pci->nCube) << 19) ^
                ((pci->fCubeOwner < 0 ? 2 : pci->fCubeOwner == pci->fMove) << 23) ^ (pci->fCrawford << 25);
        else if (pec->fCubeful || fCubefulEquity)
            /* in cubeful money games the cube position and rules are important. */
            iKey ^=
                ((pci->fCubeOwner < 0 ? 2 :
                  pci->fCubeOwner == pci->fMove) << 23) ^ (pci->fJacoby << 26) ^ (pci->fBeavers << 27);

        if (fCubefulEquity)
            iKey ^= 0x6a47b47e;
    }

    return iKey;

}

extern int
PerfectCubeful(bearoffcontext * pbc, const TanBoard anBoard, float arEquity[])
{

    unsigned int nUs = PositionBearoff(anBoard[1], pbc->nPoints, pbc->nChequers);
    unsigned int nThem = PositionBearoff(anBoard[0], pbc->nPoints, pbc->nChequers);
    unsigned int n = Combination(pbc->nPoints + pbc->nChequers, pbc->nPoints);
    unsigned int iPos = nUs * n + nThem;

    return BearoffCubeful(pbc, iPos, arEquity, NULL);

}


extern int
EvaluatePerfectCubeful(const TanBoard anBoard, float arEquity[], const bgvariation bgv)
{

    positionclass pc = ClassifyPosition(anBoard, bgv);

    g_assert(pc <= CLASS_PERFECT);

    switch (pc) {
    case CLASS_BEAROFF2:
        return PerfectCubeful(pbc2, anBoard, arEquity);
    case CLASS_BEAROFF_TS:
        return PerfectCubeful(pbcTS, anBoard, arEquity);
    default:
        g_assert_not_reached();
    }

    return -1;

}

extern void
InvertEvaluation(float ar[NUM_OUTPUTS])
{

    float r;

    ar[OUTPUT_WIN] = 1.0f - ar[OUTPUT_WIN];

    r = ar[OUTPUT_WINGAMMON];
    ar[OUTPUT_WINGAMMON] = ar[OUTPUT_LOSEGAMMON];
    ar[OUTPUT_LOSEGAMMON] = r;

    r = ar[OUTPUT_WINBACKGAMMON];
    ar[OUTPUT_WINBACKGAMMON] = ar[OUTPUT_LOSEBACKGAMMON];
    ar[OUTPUT_LOSEBACKGAMMON] = r;
}

extern void
InvertEvaluationR(float ar[NUM_ROLLOUT_OUTPUTS], const cubeinfo * pci)
{
    /* invert win, gammon etc. */

    InvertEvaluation(ar);

    /* invert equities */

    ar[OUTPUT_EQUITY] = -ar[OUTPUT_EQUITY];

    if (pci->nMatchTo)
        ar[OUTPUT_CUBEFUL_EQUITY] = 1.0f - ar[OUTPUT_CUBEFUL_EQUITY];
    else
        ar[OUTPUT_CUBEFUL_EQUITY] = -ar[OUTPUT_CUBEFUL_EQUITY];


}


extern int
GameStatus(const TanBoard anBoard, const bgvariation bgv)
{

    SSE_ALIGN(float ar[NUM_OUTPUTS]) = {
    0, 0, 0, 0, 0};             /* NUM_OUTPUTS are 5 */

    if (ClassifyPosition(anBoard, bgv) != CLASS_OVER)
        return 0;

    EvalOver(anBoard, ar, bgv, NULL);

    if (ar[OUTPUT_WINBACKGAMMON] > 0.0f || ar[OUTPUT_LOSEBACKGAMMON] > 0.0f)
        return 3;

    if (ar[OUTPUT_WINGAMMON] > 0.0f || ar[OUTPUT_LOSEGAMMON] > 0.0f)
        return 2;

    return 1;

}

/*
 * Utility returns the "correct" cubeless equity based on the current
 * gammon values.
 *
 * Use UtilityME to get the "true" money equity.
 */

extern float
Utility(float ar[NUM_OUTPUTS], const cubeinfo * pci)
{

    if (!pci->nMatchTo) {

        /* equity calculation for money game */

        /* For money game the gammon price is the same for both
         * players, so there is no need to use pci->fMove. */

        return
            ar[OUTPUT_WIN] * 2.0f - 1.0f +
            (ar[OUTPUT_WINGAMMON] - ar[OUTPUT_LOSEGAMMON]) *
            pci->arGammonPrice[0] + (ar[OUTPUT_WINBACKGAMMON] - ar[OUTPUT_LOSEBACKGAMMON]) * pci->arGammonPrice[1];

    } else {

        /* equity calculation for match play */

        return ar[OUTPUT_WIN] * 2.0f - 1.0f + ar[OUTPUT_WINGAMMON] * pci->arGammonPrice[pci->fMove]
            - ar[OUTPUT_LOSEGAMMON] * pci->arGammonPrice[!pci->fMove]
            + ar[OUTPUT_WINBACKGAMMON] * pci->arGammonPrice[2 + pci->fMove]
            - ar[OUTPUT_LOSEBACKGAMMON] * pci->arGammonPrice[2 + !pci->fMove];

    }

}

/*
 * UtilityME is identical to Utility for match play.
 * For money play it returns the money equity instead of the 
 * correct cubeless equity.
 */

extern float
UtilityME(float ar[NUM_OUTPUTS], const cubeinfo * pci)
{

    if (!pci->nMatchTo)

        /* calculate money equity */

        return
            ar[OUTPUT_WIN] * 2.0f - 1.0f +
            (ar[OUTPUT_WINGAMMON] - ar[OUTPUT_LOSEGAMMON]) + (ar[OUTPUT_WINBACKGAMMON] - ar[OUTPUT_LOSEBACKGAMMON]);

    else

        return Utility(ar, pci);

}


extern float
mwc2eq(const float rMwc, const cubeinfo * pci)
{

    /* mwc if I win/lose */

    float rMwcWin, rMwcLose;

    rMwcWin = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                    pci->fMove, pci->nCube, pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    rMwcLose = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                     pci->fMove, pci->nCube, !pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    /* 
     * make linear inter- or extrapolation:
     * equity       mwc
     *  -1          rMwcLose
     *  +1          rMwcWin
     *
     * Interpolation formula:
     *
     *       2 * rMwc - ( rMwcWin + rMwcLose )
     * rEq = ---------------------------------
     *            rMwcWin - rMwcLose
     *
     * FIXME: numerical problems?
     * If you are trailing 30-away, 1-away the difference between
     * 29-away, 1-away and 30-away, 0-away is not very large, and it may
     * give numerical problems.
     *
     */

    return (2.0f * rMwc - (rMwcWin + rMwcLose)) / (rMwcWin - rMwcLose);

}

extern float
eq2mwc(const float rEq, const cubeinfo * pci)
{

    /* mwc if I win/lose */

    float rMwcWin, rMwcLose;

    rMwcWin = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                    pci->fMove, pci->nCube, pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    rMwcLose = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                     pci->fMove, pci->nCube, !pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    /*
     * Linear inter- or extrapolation.
     * Solve the formula in the routine above (mwc2eq):
     *
     *        rEq * ( rMwcWin - rMwcLose ) + ( rMwcWin + rMwcLose )
     * rMwc = -----------------------------------------------------
     *                                   2
     */

    return 0.5f * (rEq * (rMwcWin - rMwcLose) + (rMwcWin + rMwcLose));

}

/*
 * Convert standard error MWC to standard error equity
 *
 */

extern float
se_mwc2eq(const float rMwc, const cubeinfo * pci)
{

    /* mwc if I win/lose */

    float rMwcWin, rMwcLose;

    rMwcWin = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                    pci->fMove, pci->nCube, pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    rMwcLose = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                     pci->fMove, pci->nCube, !pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    return 2.0f / (rMwcWin - rMwcLose) * rMwc;

}

/*
 * Convert standard error equity to standard error mwc
 *
 */

extern float
se_eq2mwc(const float rEq, const cubeinfo * pci)
{

    /* mwc if I win/lose */

    float rMwcWin, rMwcLose;

    rMwcWin = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                    pci->fMove, pci->nCube, pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    rMwcLose = getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                     pci->fMove, pci->nCube, !pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

    /*
     * Linear inter- or extrapolation.
     * Solve the formula in the routine above (mwc2eq):
     *
     *        rEq * ( rMwcWin - rMwcLose ) + ( rMwcWin + rMwcLose )
     * rMwc = -----------------------------------------------------
     *                                   2
     */

    return 0.5f * rEq * (rMwcWin - rMwcLose);

}

extern int
ApplySubMove(TanBoard anBoard, const int iSrc, const int nRoll, const int fCheckLegal)
{

    int iDest = iSrc - nRoll;

    if (fCheckLegal && (nRoll < 1 || nRoll > 6)) {
        /* Invalid dice roll */
        errno = EINVAL;
        return -1;
    }

    if (iSrc < 0 || iSrc > 24 || iDest > 24 || anBoard[1][iSrc] < 1) {
        /* Invalid point number, or source point is empty */
        errno = EINVAL;
        return -1;
    }

    anBoard[1][iSrc]--;

    if (iDest < 0)
        return 0;

    if (anBoard[0][23 - iDest]) {
        if (anBoard[0][23 - iDest] > 1) {
            /* Trying to move to a point already made by the opponent */
            errno = EINVAL;
            return -1;
        }
        anBoard[1][iDest] = 1;
        anBoard[0][23 - iDest] = 0;
        anBoard[0][24]++;
    } else
        anBoard[1][iDest]++;

    return 0;
}

extern int
ApplyMove(TanBoard anBoard, const int anMove[8], const int fCheckLegal)
{
    int i;

    for (i = 0; i < 8 && anMove[i] >= 0; i += 2)
        if (ApplySubMove(anBoard, anMove[i], anMove[i] - anMove[i + 1], fCheckLegal))
            return -1;

    return 0;
}

static void
SaveMoves(movelist * pml, unsigned int cMoves, unsigned int cPip, int anMoves[], const TanBoard anBoard, int fPartial)
{
    unsigned int i, j;
    move *pm;
    positionkey key;

    if (fPartial) {
        /* Save all moves, even incomplete ones */
        if (cMoves > pml->cMaxMoves)
            pml->cMaxMoves = cMoves;

        if (cPip > pml->cMaxPips)
            pml->cMaxPips = cPip;
    } else {
        /* Save only legal moves: if the current move moves plays less
         * chequers or pips than those already found, it is illegal; if
         * it plays more, the old moves are illegal. */
        if (cMoves < pml->cMaxMoves || cPip < pml->cMaxPips)
            return;

        if (cMoves > pml->cMaxMoves || cPip > pml->cMaxPips)
            pml->cMoves = 0;

        pml->cMaxMoves = cMoves;
        pml->cMaxPips = cPip;
    }

    pm = pml->amMoves + pml->cMoves;

    PositionKey(anBoard, &key);

    for (i = 0; i < pml->cMoves; i++) {
        move *pm = &(pml->amMoves[i]);

        if (EqualKeys(key, pm->key)) {
            if (cMoves > pm->cMoves || cPip > pm->cPips) {
                for (j = 0; j < cMoves * 2; j++)
                    pm->anMove[j] = anMoves[j] > -1 ? anMoves[j] : -1;

                if (cMoves < 4)
                    pm->anMove[cMoves * 2] = -1;

                pm->cMoves = cMoves;
                pm->cPips = cPip;
            }

            return;
        }
    }

    for (i = 0; i < cMoves * 2; i++)
        pm->anMove[i] = anMoves[i] > -1 ? anMoves[i] : -1;

    if (cMoves < 4)
        pm->anMove[cMoves * 2] = -1;

    CopyKey(key, pm->key);

    pm->cMoves = cMoves;
    pm->cPips = cPip;
    pm->cmark = CMARK_NONE;

    for (i = 0; i < NUM_OUTPUTS; i++)
        pm->arEvalMove[i] = 0.0;

    pml->cMoves++;

    g_assert(pml->cMoves < MAX_INCOMPLETE_MOVES);
}

static int
LegalMove(const TanBoard anBoard, int iSrc, int nPips)
{

    int nBack;
    const int iDest = iSrc - nPips;

    if (iDest >= 0) {           /* Here we can do the Chris rule check */
        return (anBoard[0][23 - iDest] < 2);
    }
    /* otherwise, attempting to bear off */

    for (nBack = 24; nBack > 0; nBack--)
        if (anBoard[1][nBack] > 0)
            break;

    return (nBack <= 5 && (iSrc == nBack || iDest == -1));
}

static int
GenerateMovesSub(movelist * pml, int anRoll[], int nMoveDepth,
                 int iPip, int cPip, const TanBoard anBoard, int anMoves[], int fPartial)
{
    int i, fUsed = 0;
    TanBoard anBoardNew;

    if (nMoveDepth > 3 || !anRoll[nMoveDepth])
        return TRUE;

    if (anBoard[1][24]) {       /* on bar */
        if (anBoard[0][anRoll[nMoveDepth] - 1] >= 2)
            return TRUE;

        anMoves[nMoveDepth * 2] = 24;
        anMoves[nMoveDepth * 2 + 1] = 24 - anRoll[nMoveDepth];

        for (i = 0; i < 25; i++) {
            anBoardNew[0][i] = anBoard[0][i];
            anBoardNew[1][i] = anBoard[1][i];
        }

        ApplySubMove(anBoardNew, 24, anRoll[nMoveDepth], TRUE);

        if (GenerateMovesSub(pml, anRoll, nMoveDepth + 1, 23, cPip +
                             anRoll[nMoveDepth], (ConstTanBoard) anBoardNew, anMoves, fPartial))
            SaveMoves(pml, nMoveDepth + 1, cPip + anRoll[nMoveDepth], anMoves, (ConstTanBoard) anBoardNew, fPartial);

        return fPartial;
    } else {
        for (i = iPip; i >= 0; i--)
            if (anBoard[1][i] && LegalMove(anBoard, i, anRoll[nMoveDepth])) {
                anMoves[nMoveDepth * 2] = i;
                anMoves[nMoveDepth * 2 + 1] = i - anRoll[nMoveDepth];

                memcpy(anBoardNew, anBoard, sizeof(anBoardNew));

                ApplySubMove(anBoardNew, i, anRoll[nMoveDepth], TRUE);

                if (GenerateMovesSub(pml, anRoll, nMoveDepth + 1,
                                     anRoll[0] == anRoll[1] ? i : 23,
                                     cPip + anRoll[nMoveDepth], (ConstTanBoard) anBoardNew, anMoves, fPartial))
                    SaveMoves(pml, nMoveDepth + 1, cPip +
                              anRoll[nMoveDepth], anMoves, (ConstTanBoard) anBoardNew, fPartial);

                fUsed = 1;
            }
    }

    return !fUsed || fPartial;
}

extern int
CompareMoves(const move * pm0, const move * pm1)
{

    /*high score first */
    return (pm1->rScore > pm0->rScore || (pm1->rScore == pm0->rScore && pm1->rScore2 > pm0->rScore2)) ? 1 : -1;
}

static int
CompareMovesGeneral(const move * pm0, const move * pm1)
{
    TanBoard board[2];
    int back[2] = { -1, -1 };
    int a, b;

    int i = cmp_evalsetup(&pm0->esMove, &pm1->esMove);

    if (i)
        return -i;              /* sort descending */

    /* find the "back" chequer */
    PositionFromKey(board[0], &pm0->key);
    PositionFromKey(board[1], &pm1->key);
    for (a = 0; a < 2; a++) {
        for (b = 24; b > -1; b--) {
            if (board[a][1][b] > 0) {
                back[a] = b;
                break;
            }
        }
    }

    /* Rounding errors when collating evaluations with lookahead make
     * comparing for equality unreliable. The first check below catches
     * situations that would be obvious and puzzling to a human opponent.
     * In general, the third check is probably not reached as often as it
     * should and, among equal moves, the most "natural" one may not
     * always be chosen. */

    /* Winning now is always at least as good as winning later */
    if (back[0] == -1)
        return -1;
    if (back[1] == -1)
        return 1;

    if (pm0->rScore != pm1->rScore || pm0->rScore2 != pm1->rScore2)
        return CompareMoves(pm0, pm1);

    /* If everything else is equal "back" chequer at high point bad */
    return (back[0] > back[1] ? 1 : -1);
}

extern int
GenerateMoves(movelist * pml, const TanBoard anBoard, int n0, int n1, int fPartial)
{

    int anRoll[4], anMoves[8];
    anRoll[0] = n0;
    anRoll[1] = n1;

    anRoll[2] = anRoll[3] = ((n0 == n1) ? n0 : 0);

    pml->cMoves = pml->cMaxMoves = pml->cMaxPips = pml->iMoveBest = 0;
    pml->amMoves = MT_Get_aMoves();
    GenerateMovesSub(pml, anRoll, 0, 23, 0, anBoard, anMoves, fPartial);

    if (anRoll[0] != anRoll[1]) {
        swap(anRoll, anRoll + 1);

        GenerateMovesSub(pml, anRoll, 0, 23, 0, anBoard, anMoves, fPartial);
    }

    return pml->cMoves;
}


extern float
KleinmanCount(int nPipOnRoll, int nPipNotOnRoll)
{
    int nDiff, nSum;
    float rK;

    nDiff = nPipNotOnRoll - nPipOnRoll;
    nSum = nPipNotOnRoll + nPipOnRoll;

    if (nSum > 4) {
        rK = (nDiff + 4) / (2 * sqrtf(nSum - 4));
        return 0.5f * (1.0f + erff(rK));
    } else
        return 0.f;
}

extern int
KeithCount(const TanBoard anBoard, int pn[2])
{
    unsigned int anPips[2];
    int i, x;
    PipCount(anBoard, anPips);
    for (i = 0; i < 2; i++) {
        pn[i] = anPips[i];
        pn[i] += (MAX(1, anBoard[i][0]) - 1) * 2;
        pn[i] += MAX(1, anBoard[i][1]) - 1;
        pn[i] += MAX(3, anBoard[i][2]) - 3;
        for (x = 3; x < 6; x++)
            if (!anBoard[i][x])
                pn[i]++;
    }
    return 0;
}

extern int
IsightCount(const TanBoard anBoard, int pn[2])
{
    unsigned int anPips[2];
    int anMenLeft[2] = { 0, 0 }, anCrossOver[2] = { 0, 0 };
    int i, x;

    PipCount(anBoard, anPips);

    for (x = 0; x < 25; x++) {
        anMenLeft[0] += anBoard[0][x];
        anMenLeft[1] += anBoard[1][x];
        anCrossOver[0] += anBoard[0][x] * (x / 6);
        anCrossOver[1] += anBoard[1][x] * (x / 6);
    }

    for (i = 0; i < 2; i++) {
        pn[i] = anPips[i];
        if (anMenLeft[i] > anMenLeft[1 - i])
            pn[i] += (anMenLeft[i] - anMenLeft[1 - i]);
        pn[i] += (MAX(2, anBoard[i][0]) - 2) * 2;
        pn[i] += MAX(2, anBoard[i][1]) - 2;
        pn[i] += MAX(3, anBoard[i][2]) - 3;
        for (x = 3; x < 6; x++)
            if (!anBoard[i][x] && anBoard[1 - i][x])
                pn[i]++;
        if (anCrossOver[i] > anCrossOver[1 - i])
            pn[i] += (anCrossOver[i] - anCrossOver[1 - i]);
    }
    return 0;
}

extern int
ThorpCount(const TanBoard anBoard, int *pnLeader, float *adjusted, int *pnTrailer)
{

    int anCovered[2], anMenLeft[2];
    int x;
    unsigned int anPips[2];

    PipCount(anBoard, anPips);

    anMenLeft[0] = 0;
    anMenLeft[1] = 0;
    for (x = 0; x < 25; x++) {
        anMenLeft[0] += anBoard[0][x];
        anMenLeft[1] += anBoard[1][x];
    }

    anCovered[0] = 0;
    anCovered[1] = 0;
    for (x = 0; x < 6; x++) {
        if (anBoard[0][x])
            anCovered[0]++;
        if (anBoard[1][x])
            anCovered[1]++;
    }

    *pnLeader = anPips[1];
    *pnLeader += 2 * anMenLeft[1];
    *pnLeader += anBoard[1][0];
    *pnLeader -= anCovered[1];
    if (*pnLeader > 30)
        *adjusted = (float) (*pnLeader * 1.1f);
    else
        *adjusted = (float) *pnLeader;

    *pnTrailer = anPips[0];
    *pnTrailer += 2 * anMenLeft[0];
    *pnTrailer += anBoard[0][0];
    *pnTrailer -= anCovered[0];

    return 0;

}


extern void
PipCount(const TanBoard anBoard, unsigned int anPips[2])
{

    int i;

    anPips[0] = 0;
    anPips[1] = 0;

    for (i = 0; i < 25; i++) {
        anPips[0] += anBoard[0][i] * (i + 1);
        anPips[1] += anBoard[1][i] * (i + 1);
    }
}



static void
StatusHypergammon1(char *sz)
{

    BearoffStatus(apbcHyper[0], sz);

}

static void
StatusHypergammon2(char *sz)
{

    BearoffStatus(apbcHyper[1], sz);

}

static void
StatusHypergammon3(char *sz)
{

    BearoffStatus(apbcHyper[2], sz);

}


static void
StatusBearoff2(char *sz)
{

    BearoffStatus(pbc2, sz);

}

static void
StatusBearoff1(char *sz)
{

    BearoffStatus(pbc1, sz);

}

static void
StatusNeuralNet(neuralnet * pnn, char *szTitle, char *sz)
{
    char buf[200];
    sz += sprintf(sz, " * %s %s:\n", szTitle, _("neural network evaluator"));
    sprintf(buf, _("version %s, %u inputs, %u hidden units"), WEIGHTS_VERSION, pnn->cInput, pnn->cHidden);
    sprintf(sz, "   - %s.\n\n", buf);
}

static void
StatusRace(char *sz)
{

    StatusNeuralNet(&nnRace, _("Race"), sz);
}

static void
StatusCrashed(char *sz)
{

    StatusNeuralNet(&nnContact, _("Crashed"), sz);
}

static void
StatusContact(char *sz)
{

    StatusNeuralNet(&nnContact, _("Contact"), sz);
}

static void
StatusOS(char *sz)
{
    BearoffStatus(pbcOS, sz);
}

static void
StatusTS(char *sz)
{
    BearoffStatus(pbcTS, sz);
}

static classstatusfunc acsf[N_CLASSES] = {
    NULL,
    StatusHypergammon1, StatusHypergammon2, StatusHypergammon3,
    StatusBearoff2, StatusTS,
    StatusBearoff1, StatusOS,
    StatusRace, StatusCrashed, StatusContact
};

extern void
EvalStatus(char *szOutput)
{

    int i;

    *szOutput = 0;

    for (i = N_CLASSES - 1; i >= 0; i--)
        if (acsf[i])
            acsf[i] (strchr(szOutput, 0));

    sprintf(strchr(szOutput, 0), _(" * " "Weights file and databases installed in" ":\n   - %s\n"), getPkgDataDir());
}


extern char
*
GetCubeRecommendation(const cubedecision cd)
{
    switch (cd) {
    case DOUBLE_TAKE:
        return _("Double, take");
    case DOUBLE_PASS:
        return _("Double, pass");
    case NODOUBLE_TAKE:
        return _("No double, take");
    case TOOGOOD_TAKE:
        return _("Too good to double, take");
    case TOOGOOD_PASS:
        return _("Too good to double, pass");
    case DOUBLE_BEAVER:
        return _("Double, beaver");
    case NODOUBLE_BEAVER:
        return _("No double, beaver");
    case REDOUBLE_TAKE:
        return _("Redouble, take");
    case REDOUBLE_PASS:
        return _("Redouble, pass");
    case NO_REDOUBLE_TAKE:
        return _("No redouble, take");
    case TOOGOODRE_TAKE:
        return _("Too good to redouble, take");
    case TOOGOODRE_PASS:
        return _("Too good to redouble, pass");
    case NO_REDOUBLE_BEAVER:
        return _("No redouble, beaver");
    case NODOUBLE_DEADCUBE:
        return _("Never double, take (dead cube)");
    case NO_REDOUBLE_DEADCUBE:
        return _("Never redouble, take (dead cube)");
    case OPTIONAL_DOUBLE_BEAVER:
        return _("Optional double, beaver");
    case OPTIONAL_DOUBLE_TAKE:
        return _("Optional double, take");
    case OPTIONAL_REDOUBLE_TAKE:
        return _("Optional redouble, take");
    case OPTIONAL_DOUBLE_PASS:
        return _("Optional double, pass");
    case OPTIONAL_REDOUBLE_PASS:
        return _("Optional redouble, pass");
    default:
        return _("Unknown cube decision");
    }
}


extern void
EvalCacheFlush(void)
{
    CacheFlush(&cEval);
}

void
CommandClearCache(char *UNUSED(sz))
{
    EvalCacheFlush();
}

extern double
GetEvalCacheSize(void)
{
    if (cEval.size == 0)
        return 0;
    else {
        double value = log(cEval.size) / log(2);
        if (value < 15)
            return 0;
        if (value < 17)
            return .5;          /* Special case for old default 65536 */
        if (value >= CACHE_SIZE_GUIMAX)
            return CACHE_SIZE_GUIMAX - 16;      /* Maximum value */
        else
            return value - 16;
    }
}

extern void
SetEvalCacheSize(unsigned int size)
{
    EvalCacheResize((size == 0) ? 0 : 1U << (size + 16));
}

extern unsigned int
GetEvalCacheEntries(void)
{
    return cCache;
}

extern int
GetCacheMB(int size)
{
    if (size <= 0)
        return 0;
    else
        return (1 << (size + 15)) * sizeof(cacheNode) / (1024 * 1024);
}

extern int
EvalCacheResize(unsigned int cNew)
{
    cCache = CacheResize(&cEval, cNew);
    return cCache;
}

extern int
EvalCacheStats(unsigned int *pcUsed, unsigned int *pcLookup, unsigned int *pcHit)
{
    CacheStats(&cEval, pcLookup, pcHit, pcUsed);
    CacheStats(&cpEval, pcLookup + 1, pcHit + 1, pcUsed + 1);
    return 0;
}

extern int
SetCubeInfoMoney(cubeinfo * pci, const int nCube, const int fCubeOwner,
                 const int fMove, const int fJacoby, const int fBeavers, const bgvariation bgv)
{

    if (nCube < 1 || fCubeOwner < -1 || fCubeOwner > 1 || fMove < 0 || fMove > 1) {     /* FIXME also illegal if nCube is not a power of 2 */
        memset(pci, 0, sizeof(cubeinfo));
        return -1;
    }

    pci->nCube = nCube;
    pci->fCubeOwner = fCubeOwner;
    pci->fMove = fMove;
    pci->fJacoby = fJacoby;
    pci->fBeavers = fBeavers;
    pci->nMatchTo = pci->anScore[0] = pci->anScore[1] = pci->fCrawford = 0;
    pci->bgv = bgv;

    pci->arGammonPrice[0] = pci->arGammonPrice[1] =
        pci->arGammonPrice[2] = pci->arGammonPrice[3] = (fJacoby && fCubeOwner == -1) ? 0.0f : 1.0f;

    return 0;
}

static int
SetCubeInfoMatch(cubeinfo * pci, const int nCube, const int fCubeOwner,
                 const int fMove, const int nMatchTo, const int anScore[2], const int fCrawford, const bgvariation bgv)
{

    if (nCube < 1 || fCubeOwner < -1 || fCubeOwner > 1 || fMove < 0 || fMove > 1 || nMatchTo < 1 || anScore[0] >= nMatchTo || anScore[1] >= nMatchTo) { /* FIXME also illegal if nCube is not a power of 2 */
        memset(pci, 0, sizeof(cubeinfo));
        return -1;
    }

    pci->nCube = nCube;
    pci->fCubeOwner = fCubeOwner;
    pci->fMove = fMove;
    pci->fJacoby = pci->fBeavers = FALSE;
    pci->nMatchTo = nMatchTo;
    pci->anScore[0] = anScore[0];
    pci->anScore[1] = anScore[1];
    pci->fCrawford = fCrawford;
    pci->bgv = bgv;

    /*
     * FIXME: calculate gammon price when initializing program
     * instead of recalculating it again and again, or cache it.
     */

    {

        int nAway0 = pci->nMatchTo - pci->anScore[0] - 1;
        int nAway1 = pci->nMatchTo - pci->anScore[1] - 1;

        if ((!nAway0 || !nAway1) && !fCrawford) {
            if (!nAway0)
                memcpy(pci->arGammonPrice, aaaafGammonPricesPostCrawford[LogCube(pci->nCube)]
                       [nAway1][0], 4 * sizeof(float));
            else
                memcpy(pci->arGammonPrice, aaaafGammonPricesPostCrawford[LogCube(pci->nCube)]
                       [nAway0][1], 4 * sizeof(float));
        } else
            memcpy(pci->arGammonPrice, aaaafGammonPrices[LogCube(pci->nCube)]
                   [nAway0][nAway1], 4 * sizeof(float));

    }

    return 0;
}

extern int
SetCubeInfo(cubeinfo * pci, const int nCube, const int fCubeOwner,
            const int fMove, const int nMatchTo, const int anScore[2],
            const int fCrawford, const int fJacoby, const int fBeavers, const bgvariation bgv)
{

    return nMatchTo ? SetCubeInfoMatch(pci, nCube, fCubeOwner, fMove,
                                       nMatchTo, anScore, fCrawford, bgv) :
        SetCubeInfoMoney(pci, nCube, fCubeOwner, fMove, fJacoby, fBeavers, bgv);
}


static int
isOptional(const float r1, const float r2)
{

    const float epsilon = 1.0e-5f;

    return (fabsf(r1 - r2) <= epsilon);

}

static int
winGammon(const float arOutput[NUM_ROLLOUT_OUTPUTS])
{

    return (arOutput[OUTPUT_WINGAMMON] > 0.0f);

}

extern cubedecision
FindBestCubeDecision(float arDouble[], float aarOutput[2][NUM_ROLLOUT_OUTPUTS], const cubeinfo * pci)
{

    /*
     * FindBestCubeDecision:
     *
     *    Calculate optimal cube decision and equity/mwc for this.
     *
     * Input:
     *    arDouble    - array with equities or mwc's:
     *                      arDouble[ 1 ]: no double,
     *                      arDouble[ 2 ]: double take
     *                      arDouble[ 3 ]: double pass
     *    pci         - pointer to cube info
     *
     * Output:
     *    arDouble    - array with equities or mwc's
     *                      arDouble[ 0 ]: equity for optimal cube decision
     *
     * Returns:
     *    cube decision 
     *
     */

    int f;

    /* Check if cube is available */

    if (!GetDPEq(NULL, NULL, pci)) {

        arDouble[OUTPUT_OPTIMAL] = arDouble[OUTPUT_NODOUBLE];

        /* for match play distinguish between dead cube and not available cube */

        if (pci->nMatchTo && (pci->fCubeOwner < 0 || pci->fCubeOwner == pci->fMove))
            return (pci->fCubeOwner == -1) ? NODOUBLE_DEADCUBE : NO_REDOUBLE_DEADCUBE;
        else
            return NOT_AVAILABLE;

    }


    /* Cube is available: find optimal cube action */

    if ((arDouble[OUTPUT_TAKE] >= arDouble[OUTPUT_NODOUBLE]) && (arDouble[OUTPUT_DROP] >= arDouble[OUTPUT_NODOUBLE])) {

        /* DT >= ND and DP >= ND */

        /* we have a double */

        if (arDouble[OUTPUT_DROP] > arDouble[OUTPUT_TAKE]) {

            /* 6. DP > DT >= ND: Double, take */

            f = isOptional(arDouble[OUTPUT_TAKE], arDouble[OUTPUT_NODOUBLE]);

            arDouble[OUTPUT_OPTIMAL] = arDouble[OUTPUT_TAKE];

            if (!pci->nMatchTo && arDouble[OUTPUT_TAKE] >= -2.0f && arDouble[OUTPUT_TAKE] <= 0.0f && pci->fBeavers) {
                if (arDouble[OUTPUT_TAKE] * 2.0f < arDouble[OUTPUT_NODOUBLE]) {
                    /*not a double if we can beaver */
                    return NODOUBLE_BEAVER;
                } else
                    /* beaver (jacoby paradox) */
                    return f ? OPTIONAL_DOUBLE_BEAVER : DOUBLE_BEAVER;
            } else {
                /* ...take */
                if (f)
                    return (pci->fCubeOwner == -1) ? OPTIONAL_DOUBLE_TAKE : OPTIONAL_REDOUBLE_TAKE;
                else
                    return (pci->fCubeOwner == -1) ? DOUBLE_TAKE : REDOUBLE_TAKE;
            }

        } else {

            /* 4. DT >= DP >= ND: Double, pass */

            /* 
             * the double is optional iff:
             * (1) equity(no double) = equity(drop)
             * (2) the player can win gammon
             * (3a) it's match play
             * or if it's money play
             * (3b) it's not a centered cube
             * or
             * (3c) the Jacoby rule is not in effect
             */

            arDouble[OUTPUT_OPTIMAL] = arDouble[OUTPUT_DROP];

            if (isOptional(arDouble[OUTPUT_NODOUBLE],
                           arDouble[OUTPUT_DROP]) &&
                (winGammon(aarOutput[0]) && (pci->nMatchTo || pci->fCubeOwner != -1 || !pci->fJacoby)))
                return (pci->fCubeOwner == -1) ? OPTIONAL_DOUBLE_PASS : OPTIONAL_REDOUBLE_PASS;
            else
                return (pci->fCubeOwner == -1) ? DOUBLE_PASS : REDOUBLE_PASS;

        }
    } else {

        /* no double */

        /* ND > DT or ND > DP */

        arDouble[OUTPUT_OPTIMAL] = arDouble[OUTPUT_NODOUBLE];

        if (arDouble[OUTPUT_NODOUBLE] > arDouble[OUTPUT_TAKE]) {

            /* ND > DT */

            if (arDouble[OUTPUT_TAKE] > arDouble[OUTPUT_DROP]) {

                /* 1. ND > DT > DP: Too good, pass */

                /* sanity check: don't play on for a gammon if none is possible... */

                if (winGammon(aarOutput[0]))
                    return (pci->fCubeOwner == -1) ? TOOGOOD_PASS : TOOGOODRE_PASS;
                else
                    return (pci->fCubeOwner == -1) ? DOUBLE_PASS : REDOUBLE_PASS;

            } else if (arDouble[OUTPUT_NODOUBLE] > arDouble[OUTPUT_DROP]) {

                /* 2. ND > DP > DT: Too good, take */

                if (winGammon(aarOutput[0]))
                    return (pci->fCubeOwner == -1) ? TOOGOOD_TAKE : TOOGOODRE_TAKE;
                else
                    return (pci->fCubeOwner == -1) ? NODOUBLE_TAKE : NO_REDOUBLE_TAKE;

            } else {

                /* 5. DP > ND > DT: No double, {take, beaver} */

                if (arDouble[OUTPUT_TAKE] >= -2.0f && arDouble[OUTPUT_TAKE] <= 0.0f && !pci->nMatchTo && pci->fBeavers)
                    return (pci->fCubeOwner == -1) ? NODOUBLE_BEAVER : NO_REDOUBLE_BEAVER;
                else
                    return (pci->fCubeOwner == -1) ? NODOUBLE_TAKE : NO_REDOUBLE_TAKE;

            }

        } else {

            /* 3. DT >= ND > DP: Too good, pass */

            if (winGammon(aarOutput[0]))
                return (pci->fCubeOwner == -1) ? TOOGOOD_PASS : TOOGOODRE_PASS;
            else
                return (pci->fCubeOwner == -1) ? DOUBLE_PASS : REDOUBLE_PASS;

        }

    }
}


extern cubedecision
FindCubeDecision(float arDouble[], float aarOutput[][NUM_ROLLOUT_OUTPUTS], const cubeinfo * pci)
{
    GetDPEq(NULL, &arDouble[OUTPUT_DROP], pci);
    arDouble[OUTPUT_NODOUBLE] = aarOutput[0][OUTPUT_CUBEFUL_EQUITY];
    arDouble[OUTPUT_TAKE] = aarOutput[1][OUTPUT_CUBEFUL_EQUITY];

    if (pci->nMatchTo) {
        /* convert to normalized money equity */

        int i;

        for (i = 1; i < 4; i++)
            arDouble[i] = mwc2eq(arDouble[i], pci);
    }

    return FindBestCubeDecision(arDouble, aarOutput, pci);
}



static int
fDoCubeful(cubeinfo * pci)
{

    if (pci->anScore[0] + pci->nCube >= pci->nMatchTo && pci->anScore[1] + pci->nCube >= pci->nMatchTo)
        /* cube is dead */
        return FALSE;

    if (pci->anScore[0] == pci->nMatchTo - 2 && pci->anScore[1] == pci->nMatchTo - 2)
        /* score is -2,-2 */
        return FALSE;

    if (pci->fCrawford)
        /* cube is dead in Crawford game */
        return FALSE;

    return TRUE;
}


extern int
GetDPEq(int *pfCube, float *prDPEq, const cubeinfo * pci)
{

    int fCube, fPostCrawford;

    if (!pci->nMatchTo) {

        /* Money game:
         * Double, pass equity for money game is 1.0 points, since we always
         * calculate equity normed to a 1-cube.
         * Take the double branch if the cube is centered or I own the cube. */

        if (prDPEq)
            *prDPEq = 1.0;

        fCube = (pci->fCubeOwner == -1) || (pci->fCubeOwner == pci->fMove);

        if (pfCube)
            *pfCube = fCube;

    } else {

        /* Match play:
         * Equity for double, pass is found from the match equity table.
         * Take the double branch is I can/will use cube:
         * - if it is not the Crawford game,
         * - and if the cube is not dead,
         * - and if it is post-Crawford and I'm trailing
         * - and if I have access to the cube.
         */

        /* FIXME: equity for double, pass */
        fPostCrawford = !pci->fCrawford &&
            (pci->anScore[0] == pci->nMatchTo - 1 || pci->anScore[1] == pci->nMatchTo - 1);

        fCube = (!pci->fCrawford) &&
            (pci->anScore[pci->fMove] + pci->nCube < pci->nMatchTo) &&
            (!(fPostCrawford && (pci->anScore[pci->fMove] == pci->nMatchTo - 1)))
            && ((pci->fCubeOwner == -1) || (pci->fCubeOwner == pci->fMove));

        if (prDPEq)
            *prDPEq =
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                      pci->fMove, pci->nCube, pci->fMove, pci->fCrawford, aafMET, aafMETPostCrawford);

        if (pfCube)
            *pfCube = fCube;

    }

    return fCube;

}


static float
MoneyLive(const float rW, const float rL, const float p, const cubeinfo * pci)
{

    if (pci->fCubeOwner == -1) {

        /* centered cube */
        float rTP = (rL - 0.5f) / (rW + rL + 0.5f);
        float rCP = (rL + 1.0f) / (rW + rL + 0.5f);

        if (p < rTP)
            /* linear interpolation between
             * (0,-rL) and ( rTP,-1) */
            return (pci->fJacoby) ? -1.0f : (-rL + (-1.0f + rL) * p / rTP);
        else if (p < rCP)
            /* linear interpolation between
             * (rTP,-1) and (rCP,+1) */
            return -1.0f + 2.0f * (p - rTP) / (rCP - rTP);
        else
            /* linear interpolation between
             * (rCP,+1) and (1,+rW) */
            return (pci->fJacoby) ? 1.0f : (+1.0f + (rW - 1.0f) * (p - rCP) / (1.0f - rCP));

    } else if (pci->fCubeOwner == pci->fMove) {

        /* owned cube */

        /* cash point */
        float rCP = (rL + 1.0f) / (rW + rL + 0.5f);

        if (p < rCP)
            /* linear interpolation between
             * (0,-rL) and (rCP,+1) */
            return -rL + (1.0f + rL) * p / rCP;
        else
            /* linear interpolation between
             * (rCP,+1) and (1,+rW) */
            return +1.0f + (rW - 1.0f) * (p - rCP) / (1.0f - rCP);

    } else {

        /* unavailable cube */

        /* take point */
        float rTP = (rL - 0.5f) / (rW + rL + 0.5f);

        if (p < rTP)
            /* linear interpolation between
             * (0,-rL) and ( rTP,-1) */
            return -rL + (-1.0f + rL) * p / rTP;
        else
            /* linear interpolation between
             * (rTP,-1) and (1,rW) */
            return -1.0f + (rW + 1.0f) * (p - rTP) / (1.0f - rTP);

    }

}


extern float
Cl2CfMoney(float arOutput[NUM_OUTPUTS], cubeinfo * pci, float rCubeX)
{
    const float epsilon = 0.0000001f;
    const float omepsilon = 0.9999999f;

    float rW, rL;
    float rEqDead, rEqLive;

    /* money game */

    /* Transform cubeless 0-ply equity to cubeful 0-ply equity using
     * Rick Janowski's formulas [insert ref here]. */

    /* First calculate average win and loss W and L: */

    if (arOutput[OUTPUT_WIN] > epsilon)
        rW = 1.0f + (arOutput[OUTPUT_WINGAMMON] + arOutput[OUTPUT_WINBACKGAMMON]) / arOutput[OUTPUT_WIN];
    else {
        /* basically a dead cube */
        return Utility(arOutput, pci);
    }

    if (arOutput[OUTPUT_WIN] < omepsilon)
        rL = 1.0f + (arOutput[OUTPUT_LOSEGAMMON] + arOutput[OUTPUT_LOSEBACKGAMMON]) / (1.0f - arOutput[OUTPUT_WIN]);
    else {
        /* basically a dead cube */
        return Utility(arOutput, pci);
    }


    rEqDead = Utility(arOutput, pci);
    rEqLive = MoneyLive(rW, rL, arOutput[OUTPUT_WIN], pci);

    return rEqDead * (1.0f - rCubeX) + rEqLive * rCubeX;

}

static float
Cl2CfMatchCentered(float arOutput[NUM_OUTPUTS], cubeinfo * pci, float rCubeX)
{

    /* normalized score */

    float rG0, rBG0, rG1, rBG1;
    float arCP[2];

    float rMWCDead, rMWCLive, rMWCWin, rMWCLose;
    float rMWCOppCash, rMWCCash, rOppTG, rTG;
    float aarMETResult[2][DTLBP1 + 1];

    /* Centered cube */

    /* Calculate normal, gammon, and backgammon ratios */

    if (arOutput[OUTPUT_WIN] > 0.0f) {
        rG0 = (arOutput[OUTPUT_WINGAMMON] - arOutput[OUTPUT_WINBACKGAMMON]) / arOutput[OUTPUT_WIN];
        rBG0 = arOutput[OUTPUT_WINBACKGAMMON] / arOutput[OUTPUT_WIN];
    } else {
        rG0 = 0.0f;
        rBG0 = 0.0f;
    }

    if (arOutput[OUTPUT_WIN] < 1.0f) {
        rG1 = (arOutput[OUTPUT_LOSEGAMMON] - arOutput[OUTPUT_LOSEBACKGAMMON]) / (1.0f - arOutput[OUTPUT_WIN]);
        rBG1 = arOutput[OUTPUT_LOSEBACKGAMMON] / (1.0f - arOutput[OUTPUT_WIN]);
    } else {
        rG1 = 0.0f;
        rBG1 = 0.0f;
    }

    /* MWC(dead cube) = cubeless equity */

    rMWCDead = eq2mwc(Utility(arOutput, pci), pci);

    /* Get live cube cash points */

    GetPoints(arOutput, pci, arCP);

    getMEMultiple(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                  pci->nCube, -1, -1, pci->fCrawford, aafMET, aafMETPostCrawford, aarMETResult[0], aarMETResult[1]);

    rMWCCash = aarMETResult[pci->fMove][NDW];

    rMWCOppCash = aarMETResult[pci->fMove][NDL];

    rOppTG = 1.0f - arCP[!pci->fMove];
    rTG = arCP[pci->fMove];

    if (arOutput[OUTPUT_WIN] <= rOppTG) {

        /* Opp too good to double */

        rMWCLose = (1.0f - rG1 - rBG1) * aarMETResult[pci->fMove][NDL]
            + rG1 * aarMETResult[pci->fMove][NDLG]
            + rBG1 * aarMETResult[pci->fMove][NDLB];

        if (rOppTG > 0.0f)
            /* avoid division by zero */
            rMWCLive = rMWCLose + (rMWCOppCash - rMWCLose) * arOutput[OUTPUT_WIN] / rOppTG;
        else
            rMWCLive = rMWCLose;

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    } else if (arOutput[OUTPUT_WIN] < rTG) {

        /* In doubling window */

        rMWCLive = rMWCOppCash + (rMWCCash - rMWCOppCash) * (arOutput[OUTPUT_WIN] - rOppTG) / (rTG - rOppTG);
        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    } else {

        /* I'm too good to double */

        /* MWC(live cube) linear interpolation between the
         * points:
         * 
         * p = TG, MWC = I win 1 point
         * p = 1, MWC = I win (normal, gammon, or backgammon)
         * 
         */

        rMWCWin = (1.0f - rG0 - rBG0) * aarMETResult[pci->fMove][NDW]
            + rG0 * aarMETResult[pci->fMove][NDWG]
            + rBG0 * aarMETResult[pci->fMove][NDWB];

        if (rTG < 1.0f)
            rMWCLive = rMWCCash + (rMWCWin - rMWCCash) * (arOutput[OUTPUT_WIN] - rTG) / (1.0f - rTG);
        else
            rMWCLive = rMWCWin;

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    }

}

static float
Cl2CfMatchOwned(float arOutput[NUM_OUTPUTS], cubeinfo * pci, float rCubeX)
{

    /* normalized score */

    float rG0, rBG0, rG1, rBG1;
    float arCP[2];

    float rMWCDead, rMWCLive, rMWCWin, rMWCLose;
    float rMWCCash, rTG;
    float aarMETResult[2][DTLBP1 + 1];

    /* I own cube */

    /* Calculate normal, gammon, and backgammon ratios */

    if (arOutput[OUTPUT_WIN] > 0.0f) {
        rG0 = (arOutput[OUTPUT_WINGAMMON] - arOutput[OUTPUT_WINBACKGAMMON]) / arOutput[OUTPUT_WIN];
        rBG0 = arOutput[OUTPUT_WINBACKGAMMON] / arOutput[OUTPUT_WIN];
    } else {
        rG0 = 0.0f;
        rBG0 = 0.0f;
    }

    if (arOutput[OUTPUT_WIN] < 1.0f) {
        rG1 = (arOutput[OUTPUT_LOSEGAMMON] - arOutput[OUTPUT_LOSEBACKGAMMON]) / (1.0f - arOutput[OUTPUT_WIN]);
        rBG1 = arOutput[OUTPUT_LOSEBACKGAMMON] / (1.0f - arOutput[OUTPUT_WIN]);
    } else {
        rG1 = 0.0;
        rBG1 = 0.0;
    }

    /* MWC(dead cube) = cubeless equity */

    rMWCDead = eq2mwc(Utility(arOutput, pci), pci);

    /* Get live cube cash points */

    GetPoints(arOutput, pci, arCP);

    getMEMultiple(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                  pci->nCube, -1, -1, pci->fCrawford, aafMET, aafMETPostCrawford, aarMETResult[0], aarMETResult[1]);

    rMWCCash = aarMETResult[pci->fMove][NDW];

    rTG = arCP[pci->fMove];

    if (arOutput[OUTPUT_WIN] <= rTG) {

        /* MWC(live cube) linear interpolation between the
         * points:
         * 
         * p = 0, MWC = I lose (normal, gammon, or backgammon)
         * p = TG, MWC = I win 1 point
         * 
         */

        rMWCLose = (1.0f - rG1 - rBG1) * aarMETResult[pci->fMove][NDL]
            + rG1 * aarMETResult[pci->fMove][NDLG]
            + rBG1 * aarMETResult[pci->fMove][NDLB];

        if (rTG > 0.0f)
            rMWCLive = rMWCLose + (rMWCCash - rMWCLose) * arOutput[OUTPUT_WIN] / rTG;
        else
            rMWCLive = rMWCLose;

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    } else {

        /* we are too good to double */

        /* MWC(live cube) linear interpolation between the
         * points:
         * 
         * p = TG, MWC = I win 1 point
         * p = 1, MWC = I win (normal, gammon, or backgammon)
         * 
         */

        rMWCWin = (1.0f - rG0 - rBG0) * aarMETResult[pci->fMove][NDW]
            + rG0 * aarMETResult[pci->fMove][NDWG]
            + rBG0 * aarMETResult[pci->fMove][NDWB];

        if (rTG < 1.0f)
            rMWCLive = rMWCCash + (rMWCWin - rMWCCash) * (arOutput[OUTPUT_WIN] - rTG) / (1.0f - rTG);
        else
            rMWCLive = rMWCWin;

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    }

}


static float
Cl2CfMatchUnavailable(float arOutput[NUM_OUTPUTS], cubeinfo * pci, float rCubeX)
{

    /* normalized score */

    float rG0, rBG0, rG1, rBG1;
    float arCP[2];

    float rMWCDead, rMWCLive, rMWCWin, rMWCLose;
    float rMWCOppCash, rOppTG;
    float aarMETResult[2][DTLBP1 + 1];

    /* I own cube */

    /* Calculate normal, gammon, and backgammon ratios */

    if (arOutput[OUTPUT_WIN] > 0.0f) {
        rG0 = (arOutput[OUTPUT_WINGAMMON] - arOutput[OUTPUT_WINBACKGAMMON]) / arOutput[OUTPUT_WIN];
        rBG0 = arOutput[OUTPUT_WINBACKGAMMON] / arOutput[OUTPUT_WIN];
    } else {
        rG0 = 0.0f;
        rBG0 = 0.0f;
    }

    if (arOutput[OUTPUT_WIN] < 1.0f) {
        rG1 = (arOutput[OUTPUT_LOSEGAMMON] - arOutput[OUTPUT_LOSEBACKGAMMON]) / (1.0f - arOutput[OUTPUT_WIN]);
        rBG1 = arOutput[OUTPUT_LOSEBACKGAMMON] / (1.0f - arOutput[OUTPUT_WIN]);
    } else {
        rG1 = 0.0;
        rBG1 = 0.0;
    }

    /* MWC(dead cube) = cubeless equity */

    rMWCDead = eq2mwc(Utility(arOutput, pci), pci);

    /* Get live cube cash points */

    GetPoints(arOutput, pci, arCP);

    getMEMultiple(pci->anScore[0], pci->anScore[1], pci->nMatchTo,
                  pci->nCube, -1, -1, pci->fCrawford, aafMET, aafMETPostCrawford, aarMETResult[0], aarMETResult[1]);

    rMWCOppCash = aarMETResult[pci->fMove][NDL];

    rOppTG = 1.0f - arCP[!pci->fMove];

    if (arOutput[OUTPUT_WIN] <= rOppTG) {

        /* Opponent is too good to double.
         * 
         * MWC(live cube) linear interpolation between the
         * points:
         * 
         * p = 0, MWC = opp win normal, gammon, backgammon
         * p = OppTG, MWC = opp cashes
         * 
         */

        rMWCLose = (1.0f - rG1 - rBG1) * aarMETResult[pci->fMove][NDL]
            + rG1 * aarMETResult[pci->fMove][NDLG]
            + rBG1 * aarMETResult[pci->fMove][NDLB];

        if (rOppTG > 0.0f)
            /* avoid division by zero */
            rMWCLive = rMWCLose + (rMWCOppCash - rMWCLose) * arOutput[OUTPUT_WIN] / rOppTG;
        else
            rMWCLive = rMWCLose;

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    } else {

        /* MWC(live cube) linear interpolation between the
         * points:
         * 
         * p = OppTG, MWC = opponent cashes
         * p = 1, MWC = I win (normal, gammon, or backgammon)
         * 
         */

        rMWCWin = (1.0f - rG0 - rBG0) * aarMETResult[pci->fMove][NDW]
            + rG0 * aarMETResult[pci->fMove][NDWG]
            + rBG0 * aarMETResult[pci->fMove][NDWB];

        rMWCLive = rMWCOppCash + (rMWCWin - rMWCOppCash) * (arOutput[OUTPUT_WIN] - rOppTG) / (1.0f - rOppTG);

        /* (1-x) MWC(dead) + x MWC(live) */

        return rMWCDead * (1.0f - rCubeX) + rMWCLive * rCubeX;

    }

}


extern float
Cl2CfMatch(float arOutput[NUM_OUTPUTS], cubeinfo * pci, float rCubeX)
{
    /* Check if this requires a cubeful evaluation */

    if (!fDoCubeful(pci)) {

        /* cubeless eval */

        return eq2mwc(Utility(arOutput, pci), pci);

    } /* fDoCubeful */
    else {

        /* cubeful eval */

        if (pci->fCubeOwner == -1)
            return Cl2CfMatchCentered(arOutput, pci, rCubeX);
        else if (pci->fCubeOwner == pci->fMove)
            return Cl2CfMatchOwned(arOutput, pci, rCubeX);
        else
            return Cl2CfMatchUnavailable(arOutput, pci, rCubeX);

    }

}



extern float
EvalEfficiency(const TanBoard anBoard, positionclass pc)
{
    /* Since it's somewhat costly to call CalcInputs, the 
     * inputs should preferably be cached to save time. */

    switch (pc) {
    case CLASS_OVER:
        return 0.0f;            /* dead cube */

    case CLASS_HYPERGAMMON1:
    case CLASS_HYPERGAMMON2:
    case CLASS_HYPERGAMMON3:

        /* FIXME */

        return 0.60f;

    case CLASS_BEAROFF1:
    case CLASS_BEAROFF_OS:
        /* FIXME: calculate based on #rolls to get off.
         * For example, 15 rolls probably have cube eff. of
         * 0.7, and 1.25 rolls have cube eff. of 1.0.
         * 
         * It's not so important to have cube eff. correct here as an
         * n-ply evaluation will take care of last-roll and 2nd-last-roll
         * situations. */

        return rOSCubeX;

    case CLASS_RACE:
        {
            unsigned int anPips[2];

            float rEff;

            PipCount(anBoard, anPips);

            rEff = anPips[1] * rRaceFactorX + rRaceCoefficientX;
            if (rEff > rRaceMax)
                return rRaceMax;
            else {
                if (rEff < rRaceMin)
                    return rRaceMin;
                else
                    return rEff;
            }
        }

    case CLASS_CONTACT:

        /* FIXME: should CLASS_CRASHED be handled differently? */

        /* FIXME: use Oystein's values published in rec.games.backgammon,
         * or work some other semiempirical values */

        /* FIXME: very important: use opponents inputs as well */

        return rContactX;

    case CLASS_CRASHED:

        return rCrashedX;

    case CLASS_BEAROFF2:
    case CLASS_BEAROFF_TS:

        return rTSCubeX;        /* for match play only */

    default:
        g_assert_not_reached();

    }
    return 0;

}


extern char *
FormatEval(char *sz, evalsetup * pes)
{

    switch (pes->et) {
    case EVAL_NONE:
        strcpy(sz, "");
        break;
    case EVAL_EVAL:
        sprintf(sz, "%s %1u-%s", pes->ec.fCubeful ? _("Cubeful") : _("Cubeless"), pes->ec.nPlies, _("ply"));
        break;
    case EVAL_ROLLOUT:
        sprintf(sz, "%s", _("Rollout"));
        break;
    default:
        sprintf(sz, "Unknown (%d)", (int) pes->et);
        break;
    }

    return sz;

}

#if 0
static void
CalcCubefulEquity(positionclass pc, float arOutput[NUM_ROLLOUT_OUTPUTS], int nPlies, int fDT, cubeinfo * pci)
{

    float rND, rDT, rDP, r;
    int fCube;
    cubeinfo ci;
    float ar[NUM_ROLLOUT_OUTPUTS];

    int fMax = !(nPlies % 2);

    memcpy(&ar[0], &arOutput[0], NUM_OUTPUTS * sizeof(float));

    if (!nPlies) {

        /* leaf node */

        if (pc == CLASS_OVER || (pci->nMatchTo && !fDoCubeful(pci))) {

            /* cubeless */

            rND = Utility(arOutput, pci);

        } else {

            /* cubeful */

            rND = (pci->nMatchTo) ? mwc2eq(Cl2CfMatch(arOutput, pci), pci) : Cl2CfMoney(arOutput, pci);

        }

    } else {

        /* internal node; recurse */

        SetCubeInfo(&ci,
                    pci->nCube, pci->fCubeOwner,
                    !pci->fMove, pci->nMatchTo, pci->anScore, pci->fCrawford, pci->fJacoby, pci->fBeavers, pci->bgv);

        CalcCubefulEquity(pc, ar, nPlies - 1, TRUE, &ci);

        rND = ar[OUTPUT_CUBEFUL_EQUITY];

    }

    GetDPEq(&fCube, &rDP, pci);

    if (pci->nMatchTo)
        rDP = mwc2eq(rDP, pci);

    if (fCube && fDT) {

        /* double, take */

        if (!nPlies) {

            SetCubeInfo(&ci, 2 * pci->nCube, !pci->fMove, pci->fMove,
                        pci->nMatchTo, pci->anScore, pci->fCrawford, pci->fJacoby, pci->fBeavers, pci->bgv);

            /* leaf node */

            if (pc == CLASS_OVER || (pci->nMatchTo && !fDoCubeful(&ci))) {

                /* cubeless */

                rDT = Utility(arOutput, &ci);
                if (pci->nMatchTo)
                    rDT *= 2.0;

            } else {

                /* cubeful */

                rDT = (pci->nMatchTo) ? mwc2eq(Cl2CfMatch(arOutput, &ci), &ci) : 2.0 * Cl2CfMoney(arOutput, &ci);

            }

        } else {

            /* internal node; recurse */

            SetCubeInfo(&ci, 2 * pci->nCube, !pci->fMove, !pci->fMove,
                        pci->nMatchTo, pci->anScore, pci->fCrawford, pci->fJacoby, pci->fBeavers, pci->bgv);

            CalcCubefulEquity(pc, ar, nPlies - 1, TRUE, &ci);

            rDT = ar[OUTPUT_CUBEFUL_EQUITY];
            if (!ci.nMatchTo)
                rDT *= 2.0;

        }

        if (fMax) {

            /* maximize my equity */

            if (rDP > rND && rDT > rND) {

                /* it's a double */

                if (rDT >= rDP)
                    r = rDP;    /* pass */
                else
                    r = rDT;    /* take */

            } else
                r = rND;        /* no double */

        } else {

            /* minimize my equity */

            rDP = -rDP;

            if (rDP < rND && rDT < rND) {

                /* it's a double */

                if (rDT < rDP)
                    r = rDP;    /* pass */
                else
                    r = rDT;    /* take */

            } else
                r = rND;        /* no double */

        }
    } else {
        r = rND;
        rDT = 0.0;
    }

    arOutput[OUTPUT_EQUITY] = UtilityME(arOutput, pci);
    arOutput[OUTPUT_CUBEFUL_EQUITY] = r;

}
#endif                          /* !LOCKING_VERSION */


/*
 * Compare two evalcontexts.
 *
 * Input:
 *    - pec1, pec2: the two evalcontexts to compare
 *
 * Output:
 *    None.
 *
 * Returns:
 *    -1 if  *pec1 "<" *pec2
 *     0 if  *pec1 "=" *pec2
 *    +1 if  *pec1 ">" *pec2
 *
 */

extern int
cmp_evalcontext(const evalcontext * pec1, const evalcontext * pec2)
{

    /* Check if plies are different */

    if (pec1->nPlies < pec2->nPlies)
        return -1;
    else if (pec1->nPlies > pec2->nPlies)
        return +1;

    /* Check for cubeful evals */

    if (pec1->fCubeful < pec2->fCubeful)
        return -1;
    else if (pec1->fCubeful > pec2->fCubeful)
        return +1;

    /* Noise  */

    if (pec1->rNoise > pec2->rNoise)
        return -1;
    else if (pec1->rNoise < pec2->rNoise)
        return +1;

    if (pec1->rNoise > 0) {

        if (pec1->fDeterministic < pec2->fDeterministic)
            return -1;
        else if (pec1->fDeterministic > pec2->fDeterministic)
            return +1;

    }

    if (pec1->nPlies > 0) {
        int nPrune1 = (pec1->fUsePrune);
        int nPrune2 = (pec2->fUsePrune);
        if (nPrune1 > nPrune2)
            return -1;
        else if (nPrune1 < nPrune2)
            return +1;
    }

    return 0;

}


/*
 * Compare two rolloutcontexts.
 *
 * Input:
 *    - prc1, prc2: the two evalsetups to compare
 *
 * Output:
 *    None.
 *
 * Returns:
 *    -1 if  *prc1 "<" *prc2
 *     0 if  *prc1 "=" *prc2
 *    +1 if  *prc1 ">" *prc2
 *
 */

static int
cmp_rolloutcontext(const rolloutcontext * UNUSED(prc1), const rolloutcontext * UNUSED(prc2))
{

    /* FIXME: write me */

    return 0;


}


/*
 * Compare two evalsetups.
 *
 * Input:
 *    - pes1, pes2: the two evalsetups to compare
 *
 * Output:
 *    None.
 *
 * Returns:
 *    -1 if  *pes1 "<" *pes2
 *     0 if  *pes1 "=" *pes2
 *    +1 if  *pes1 ">" *pes2
 *
 */

extern int
cmp_evalsetup(const evalsetup * pes1, const evalsetup * pes2)
{

    /* Check for different evaltypes */

    if (pes1->et < pes2->et)
        return -1;
    else if (pes1->et > pes2->et)
        return +1;

    /* The two evaltypes are identical */

    switch (pes1->et) {
    case EVAL_NONE:
        return 0;

    case EVAL_EVAL:
        return cmp_evalcontext(&pes1->ec, &pes2->ec);

    case EVAL_ROLLOUT:
        return cmp_rolloutcontext(&pes1->rc, &pes2->rc);

    default:
        g_assert_not_reached();
    }

    return 0;
}


static void
calculate_gammon_rates(float aarRates[2][2], float arOutput[], cubeinfo * pci)
{

    if (arOutput[OUTPUT_WIN] > 0.0f) {
        aarRates[pci->fMove][0] = (arOutput[OUTPUT_WINGAMMON] - arOutput[OUTPUT_WINBACKGAMMON]) / arOutput[OUTPUT_WIN];
        aarRates[pci->fMove][1] = arOutput[OUTPUT_WINBACKGAMMON] / arOutput[OUTPUT_WIN];
    } else {
        aarRates[pci->fMove][0] = aarRates[pci->fMove][1] = 0.0f;
    }

    if (arOutput[OUTPUT_WIN] < 1.0f) {
        aarRates[!pci->fMove][0] =
            (arOutput[OUTPUT_LOSEGAMMON] - arOutput[OUTPUT_LOSEBACKGAMMON]) / (1.0f - arOutput[OUTPUT_WIN]);
        aarRates[!pci->fMove][1] = arOutput[OUTPUT_LOSEBACKGAMMON] / (1.0f - arOutput[OUTPUT_WIN]);
    } else {
        aarRates[!pci->fMove][0] = aarRates[!pci->fMove][1] = 0.0f;
    }

}

/*
 * Get current gammon rates
 *
 * Input:
 *   anBoard: current board
 *   pci: current cubeinfo
 *   pec: eval context
 *
 * Output:
 *   aarRates: gammon and backgammon rates (first index is player)
 *
 */

extern int
getCurrentGammonRates(float aarRates[2][2],
                      float arOutput[], const TanBoard anBoard, cubeinfo * pci, const evalcontext * pec)
{

    if (EvaluatePosition(NULL, anBoard, arOutput, pci, pec) < 0)
        return -1;

    calculate_gammon_rates(aarRates, arOutput, pci);

    return 0;

}

/*
 * Get take, double, beaver, etc points for money game using
 * Rick Janowski's formulae:
 *   http://www.bkgm.com/articles/Janowski/cubeformulae.pdf
 *
 * Input:
 *   fJacoby, fBeavers: flags for different flavours of money game
 *   aarRates: gammon and backgammon rates (first index is player)
 *
 * Output:
 *   aaarPoints: the points
 *
 */

extern void
getMoneyPoints(float aaarPoints[2][7][2], const int fJacoby, const int fBeavers, float aarRates[2][2])
{

    float arCLV[2];             /* average cubeless value of games won */
    float rW, rL;
    int i;

    /* calculate average cubeless value of games won */

    for (i = 0; i < 2; i++)
        arCLV[i] = 1.0f + aarRates[i][0] + 2.0f * aarRates[i][1];

    /* calculate points */

    for (i = 0; i < 2; i++) {

        /* Determine rW and rL from Rick's formulae */

        rW = arCLV[i];
        rL = arCLV[!i];

        /* Determine points */

        /* take point */

        aaarPoints[i][0][0] = (rL - 0.5f) / (rW + rL);
        aaarPoints[i][0][1] = (rL - 0.5f) / (rW + rL + 0.5f);

        /* beaver point */

        aaarPoints[i][1][0] = rL / (rW + rL);
        aaarPoints[i][1][1] = rL / (rW + rL + 0.5f);

        /* raccoon point */

        aaarPoints[i][2][0] = rL / (rW + rL);
        aaarPoints[i][2][1] = (rL + 0.5f) / (rW + rL + 0.5f);

        /* initial double point */

        if (!fJacoby) {
            /* without Jacoby */
            aaarPoints[i][3][0] = rL / (rW + rL);
        } else {
            /* with Jacoby */

            if (fBeavers)
                /* with beavers */
                aaarPoints[i][3][0] = (rL - 0.25f) / (rL + rW - 0.5f);
            else
                /* without beavers */
                aaarPoints[i][3][0] = (rL - 0.5f) / (rL + rW - 1.0f);

        }
        aaarPoints[i][3][1] = (rL + 1.0f) / (rL + rW + 0.5f);

        /* redouble point */
        aaarPoints[i][4][0] = rL / (rW + rL);
        aaarPoints[i][4][1] = (rL + 1.0f) / (rL + rW + 0.5f);

        /* cash point */

        aaarPoints[i][5][0] = (rL + 0.5f) / (rW + rL);
        aaarPoints[i][5][1] = (rL + 1.0f) / (rW + rL + 0.5f);

        /* too good point */

        aaarPoints[i][6][0] = (rL + 1.0f) / (rW + rL);
        aaarPoints[i][6][1] = (rL + 1.0f) / (rW + rL + 0.5f);

    }

}

extern void
GetECF3(float arCubeful[], int cci, float arCf[], cubeinfo aci[])
{

    int i, ici;
    float rND, rDT, rDP;

    for (ici = 0, i = 0; ici < cci; ici++, i += 2) {

        if (aci[i + 1].nCube > 0) {

            /* cube available */

            rND = arCf[i];

            if (aci[0].nMatchTo)
                rDT = arCf[i + 1];
            else
                rDT = 2.0f * arCf[i + 1];

            GetDPEq(NULL, &rDP, &aci[i]);

            if (rDT >= rND && rDP >= rND) {

                /* double */

                if (rDT >= rDP)
                    /* pass */
                    arCubeful[ici] = rDP;
                else
                    /* take */
                    arCubeful[ici] = rDT;

            } else {

                /* no double */

                arCubeful[ici] = rND;

            }


        } else {

            /* no cube available: always no double */

            arCubeful[ici] = arCf[i];

        }

    }

}


extern void
MakeCubePos(const cubeinfo aciCubePos[], const int cci, const int fTop, cubeinfo aci[], const int fInvert)
{
    int i, ici;

    for (ici = 0, i = 0; ici < cci; ici++) {

        /* no double */

        if (aciCubePos[ici].nCube > 0) {

            SetCubeInfo(&aci[i],
                        aciCubePos[ici].nCube,
                        aciCubePos[ici].fCubeOwner,
                        fInvert ?
                        !aciCubePos[ici].fMove : aciCubePos[ici].fMove,
                        aciCubePos[ici].nMatchTo,
                        aciCubePos[ici].anScore,
                        aciCubePos[ici].fCrawford,
                        aciCubePos[ici].fJacoby, aciCubePos[ici].fBeavers, aciCubePos[ici].bgv);

        } else {

            aci[i].nCube = -1;

        }

        i++;

        if (!fTop && aciCubePos[ici].nCube > 0 && GetDPEq(NULL, NULL, &aciCubePos[ici]))
            /* we may double */
            SetCubeInfo(&aci[i],
                        2 * aciCubePos[ici].nCube,
                        !aciCubePos[ici].fMove,
                        fInvert ?
                        !aciCubePos[ici].fMove : aciCubePos[ici].fMove,
                        aciCubePos[ici].nMatchTo,
                        aciCubePos[ici].anScore,
                        aciCubePos[ici].fCrawford,
                        aciCubePos[ici].fJacoby, aciCubePos[ici].fBeavers, aciCubePos[ici].bgv);
        else
            /* mark cube position as unavailable */
            aci[i].nCube = -1;

        i++;


    }                           /* loop cci */

}


/*
 * Get take, double, take, and too good points for match play.
 *
 * Input:
 *   pci: cubeinfo 
 *   aarRates: gammon and backgammon rates (first index is player)
 *
 * Output:
 *   aaarPoints: the points
 *
 */

extern void
getMatchPoints(float aaarPoints[2][4][2],
               int afAutoRedouble[2], int afDead[2], const cubeinfo * pci, float aarRates[2][2])
{

    SSE_ALIGN(float arOutput[NUM_OUTPUTS]);
    float arDP1[2], arDP2[2], arCP1[2], arCP2[2], arTG[2];
    float rDTW, rDTL, rNDW, rNDL, rDP, rRisk, rGain;

    int i, anNormScore[2];

    for (i = 0; i < 2; i++)
        anNormScore[i] = pci->nMatchTo - pci->anScore[i];

    /* get cash points */

    arOutput[OUTPUT_WIN] = 0.5f;
    arOutput[OUTPUT_WINGAMMON] = 0.5f * (aarRates[0][0] + aarRates[0][1]);
    arOutput[OUTPUT_WINBACKGAMMON] = 0.5f * aarRates[0][1];
    arOutput[OUTPUT_LOSEGAMMON] = 0.5f * (aarRates[1][0] + aarRates[1][1]);
    arOutput[OUTPUT_LOSEBACKGAMMON] = 0.5f * aarRates[1][1];

    GetPoints(arOutput, pci, arCP2);

    for (i = 0; i < 2; i++) {

        afAutoRedouble[i] = (anNormScore[i] - 2 * pci->nCube <= 0) && (anNormScore[!i] - 2 * pci->nCube > 0);

        afDead[i] = (anNormScore[!i] - 2 * pci->nCube <= 0);

        /* MWC for "double, take; win" */

        rDTW =
            (1.0f - aarRates[i][0] - aarRates[i][1]) *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  2 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[i][0] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  4 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[i][1] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  6 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford);

        /* MWC for "no double, take; win" */

        rNDW =
            (1.0f - aarRates[i][0] - aarRates[i][1]) *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[i][0] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  2 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[i][1] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  3 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford);

        /* MWC for "Double, take; lose" */

        rDTL =
            (1.0f - aarRates[!i][0] - aarRates[!i][1]) *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  2 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[!i][0] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  4 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[!i][1] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  6 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford);

        /* MWC for "No double; lose" */

        rNDL =
            (1.0f - aarRates[!i][0] - aarRates[!i][1]) *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  1 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[!i][0] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  2 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
            + aarRates[!i][1] *
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  3 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford);

        /* MWC for "Double, pass" */

        rDP =
            getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                  pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford);

        /* Double point */

        rRisk = rNDL - rDTL;
        rGain = rDTW - rNDW;

        arDP1[i] = rRisk / (rRisk + rGain);
        arDP2[i] = arDP1[i];

        /* Dead cube take point without redouble */

        rRisk = rDTW - rDP;
        rGain = rDP - rDTL;

        arCP1[i] = 1.0f - rRisk / (rRisk + rGain);

        /* find too good point */

        rRisk = rNDW - rNDL;
        rGain = rNDW - rDP;

        arTG[i] = rRisk / (rRisk + rGain);

        if (afAutoRedouble[i]) {

            /* With redouble */

            rDTW =
                (1.0f - aarRates[i][0] - aarRates[i][1]) *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      4 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
                + aarRates[i][0] *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      8 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford)
                + aarRates[i][1] *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      12 * pci->nCube, i, pci->fCrawford, aafMET, aafMETPostCrawford);

            rDTL =
                (1.0f - aarRates[!i][0] - aarRates[!i][1]) *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      4 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
                + aarRates[!i][0] *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      8 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford)
                + aarRates[!i][1] *
                getME(pci->anScore[0], pci->anScore[1], pci->nMatchTo, i,
                      12 * pci->nCube, !i, pci->fCrawford, aafMET, aafMETPostCrawford);

            rRisk = rDTW - rDP;
            rGain = rDP - rDTL;

            arCP2[i] = 1.0f - rRisk / (rRisk + rGain);

            /* Double point */

            rRisk = rNDL - rDTL;
            rGain = rDTW - rNDW;

            arDP2[i] = rRisk / (rRisk + rGain);

        }

    }

    /* save points */

    for (i = 0; i < 2; i++) {

        /* take point */

        aaarPoints[i][0][0] = 1.0f - arCP1[!i];
        aaarPoints[i][0][1] = 1.0f - arCP2[!i];

        /* double point */

        aaarPoints[i][1][0] = arDP1[i];
        aaarPoints[i][1][1] = arDP2[i];

        /* cash point */

        aaarPoints[i][2][0] = arCP1[i];
        aaarPoints[i][2][1] = arCP2[i];

        /* too good point */

        aaarPoints[i][3][0] = arTG[i];

        if (!afDead[i])
            aaarPoints[i][3][1] = arCP2[i];

    }

}

extern void
getCubeDecisionOrdering(int aiOrder[3],
                        float arDouble[4], float aarOutput[2][NUM_ROLLOUT_OUTPUTS], const cubeinfo * pci)
{

    cubedecision cd;

    /* Get cube decision */

    cd = FindBestCubeDecision(arDouble, aarOutput, pci);

    switch (cd) {

    case DOUBLE_TAKE:
    case DOUBLE_BEAVER:
    case REDOUBLE_TAKE:

        /*
         * Optimal     : Double, take
         * Best for me : Double, pass
         * Worst for me: No Double 
         */

        aiOrder[0] = OUTPUT_TAKE;
        aiOrder[1] = OUTPUT_DROP;
        aiOrder[2] = OUTPUT_NODOUBLE;

        break;

    case DOUBLE_PASS:
    case REDOUBLE_PASS:

        /*
         * Optimal     : Double, pass
         * Best for me : Double, take
         * Worst for me: no double 
         */
        aiOrder[0] = OUTPUT_DROP;
        aiOrder[1] = OUTPUT_TAKE;
        aiOrder[2] = OUTPUT_NODOUBLE;

        break;

    case NODOUBLE_TAKE:
    case NODOUBLE_BEAVER:
    case TOOGOOD_TAKE:
    case NO_REDOUBLE_TAKE:
    case NO_REDOUBLE_BEAVER:
    case TOOGOODRE_TAKE:
    case NODOUBLE_DEADCUBE:
    case NO_REDOUBLE_DEADCUBE:
    case OPTIONAL_DOUBLE_BEAVER:
    case OPTIONAL_DOUBLE_TAKE:
    case OPTIONAL_REDOUBLE_TAKE:

        /*
         * Optimal     : no double
         * Best for me : double, pass
         * Worst for me: double, take
         */

        aiOrder[0] = OUTPUT_NODOUBLE;
        aiOrder[1] = OUTPUT_DROP;
        aiOrder[2] = OUTPUT_TAKE;

        break;

    case TOOGOOD_PASS:
    case TOOGOODRE_PASS:
    case OPTIONAL_DOUBLE_PASS:
    case OPTIONAL_REDOUBLE_PASS:

        /*
         * Optimal     : no double
         * Best for me : double, take
         * Worst for me: double, pass
         */

        aiOrder[0] = OUTPUT_NODOUBLE;
        aiOrder[1] = OUTPUT_TAKE;
        aiOrder[2] = OUTPUT_DROP;

        break;

    default:

        g_assert_not_reached();

    }

}



extern float
getPercent(const cubedecision cd, const float arDouble[])
{

    switch (cd) {

    case DOUBLE_TAKE:
    case DOUBLE_BEAVER:
    case DOUBLE_PASS:
    case REDOUBLE_TAKE:
    case REDOUBLE_PASS:
    case NODOUBLE_DEADCUBE:
    case NO_REDOUBLE_DEADCUBE:
    case OPTIONAL_DOUBLE_BEAVER:
    case OPTIONAL_DOUBLE_TAKE:
    case OPTIONAL_REDOUBLE_TAKE:
    case OPTIONAL_DOUBLE_PASS:
    case OPTIONAL_REDOUBLE_PASS:
        /* correct cube action */
        return -1.0f;

    case TOOGOODRE_TAKE:
    case TOOGOOD_TAKE:
        /* never correct to double */
        return -1.0f;

    case NODOUBLE_TAKE:
    case NODOUBLE_BEAVER:
    case NO_REDOUBLE_TAKE:
    case NO_REDOUBLE_BEAVER:

        /* how many doubles should be dropped before it is correct to double */

        return (arDouble[OUTPUT_NODOUBLE] - arDouble[OUTPUT_TAKE]) / (arDouble[OUTPUT_DROP] - arDouble[OUTPUT_TAKE]);

    case TOOGOOD_PASS:
    case TOOGOODRE_PASS:

        /* how many doubles should be taken before it is correct to double */
        if (arDouble[OUTPUT_NODOUBLE] > arDouble[OUTPUT_TAKE])
            /* strange match play scenario 
             * (see 3-ply eval on cAmgACAAGAAA/4HPkAUgzW8EBMA):
             * never correct to double! */
            return -1.0f;
        else
            return
                (arDouble[OUTPUT_NODOUBLE] - arDouble[OUTPUT_DROP]) / (arDouble[OUTPUT_TAKE] - arDouble[OUTPUT_DROP]);

    default:

        g_assert_not_reached();

    }

    return -1.0f;
}


/*
 * Resort movelist and recalculate best score.
 *
 * Input:
 *   pml: movelist
 *
 * Output:
 *   pml: update movelist
 *   ai : the new ordering. Caller must allocate ai.
 *
 * FIXME: the construction of the ai-array is *very* ugly.
 *        We should probably write a substitute for qsort that
 *        updates ai on the fly.
 *
 */

extern void
RefreshMoveList(movelist * pml, int *ai)
{

    unsigned int i, j;
    movelist ml;

    if (!pml->cMoves)
        return;

    if (ai)
        CopyMoveList(&ml, pml);

    qsort(pml->amMoves, pml->cMoves, sizeof(move), (cfunc) CompareMovesGeneral);

    pml->rBestScore = pml->amMoves[0].rScore;

    if (ai) {
        for (i = 0; i < pml->cMoves; i++) {

            for (j = 0; j < pml->cMoves; j++) {

                if (!memcmp(ml.amMoves[j].anMove, pml->amMoves[i].anMove, 8 * sizeof(int)))
                    ai[j] = i;

            }
        }

        free(ml.amMoves);

    }


}


extern void
CopyMoveList(movelist * pmlDest, const movelist * pmlSrc)
{

    if (pmlDest == pmlSrc)
        return;

    pmlDest->cMoves = pmlSrc->cMoves;
    pmlDest->cMaxMoves = pmlSrc->cMaxMoves;
    pmlDest->cMaxPips = pmlSrc->cMaxPips;
    pmlDest->iMoveBest = pmlSrc->iMoveBest;
    pmlDest->rBestScore = pmlSrc->rBestScore;

    if (pmlSrc->cMoves) {
        pmlDest->amMoves = (move *) malloc(pmlSrc->cMoves * sizeof(move));
        memcpy(pmlDest->amMoves, pmlSrc->amMoves, pmlSrc->cMoves * sizeof(move));
    } else
        pmlDest->amMoves = NULL;

}



/*
 * is this a close cubedecision?
 *
 * Input:
 *   arDouble: equities for cube decisions
 *
 */

extern int
isCloseCubedecision(const float arDouble[])
{
    const float rThr = 0.16f;
    float rDouble;
    rDouble = MIN(arDouble[OUTPUT_TAKE], 1.0f);

    /* Report if doubling is less than very bad (0.16) */
    if (arDouble[OUTPUT_OPTIMAL] - rDouble < rThr)
        return 1;

    return 0;

}


/*
 * is this a missed double?
 *
 * Input:
 *   arDouble: equities for cube decisions
 *   fDouble: did the player double
 *   pci: cubeinfo
 *
 */

extern int
isMissedDouble(float arDouble[], float aarOutput[2][NUM_ROLLOUT_OUTPUTS], const int fDouble, const cubeinfo * pci)
{

    cubedecision cd = FindBestCubeDecision(arDouble, aarOutput, pci);

    switch (cd) {

    case DOUBLE_TAKE:
    case DOUBLE_PASS:
    case DOUBLE_BEAVER:
    case REDOUBLE_TAKE:
    case REDOUBLE_PASS:

        return !fDouble;

    default:

        return 0;

    }

}


static int
MoveKey(const TanBoard anBoard, const int anMove[8], positionkey * pkey)
{
    TanBoard anBoardMove;

    memcpy(anBoardMove, anBoard, sizeof(anBoardMove));
    ApplyMove(anBoardMove, anMove, FALSE);
    PositionKey((ConstTanBoard) anBoardMove, pkey);

    return 0;
}


extern unsigned int
locateMove(const TanBoard anBoard, const int anMove[8], const movelist * pml)
{

    unsigned int i;
    positionkey key1, key2;

    MoveKey(anBoard, anMove, &key1);

    for (i = 0; i < pml->cMoves; ++i) {

        MoveKey(anBoard, pml->amMoves[i].anMove, &key2);

        if (EqualKeys(key2, key1))
            return i;


    }

    return 0;

}


extern int
equal_movefilter(const int i, const movefilter amf1[MAX_FILTER_PLIES], const movefilter amf2[MAX_FILTER_PLIES])
{

    int j;

    for (j = 0; j <= i; ++j) {
        if (amf1[j].Accept != amf2[j].Accept)
            return 0;
        if (amf1[j].Accept < 0)
            continue;
        if (amf1[j].Extra != amf2[j].Extra)
            return 0;
        if (!amf1[j].Extra)
            continue;
        if (amf1[j].Threshold != amf2[j].Threshold)
            return 0;

    }

    return 1;

}


extern int
equal_movefilters(movefilter aamf1[MAX_FILTER_PLIES][MAX_FILTER_PLIES],
                  movefilter aamf2[MAX_FILTER_PLIES][MAX_FILTER_PLIES])
{

    int i;

    for (i = 0; i < MAX_FILTER_PLIES; ++i)
        if (!equal_movefilter(i, aamf1[i], aamf2[i]))
            return 0;

    return 1;

}


/*
 * Categorise double into normal, beaver, or raccoon.
 * 
 * The function is called before ApplyMoveRecord:
 *
 * fDoubled = FALSE:
 *
 *    the previous moverecord was not a MOVE_DOUBLE,
 *    hence this is a normal double.
 *
 * fDoubled = TRUE:
 *
 *    The previous moverecord was a MOVE_DOUBLE
 *    so it's either a beaver or a raccoon
 *
 *    Beaver: fTurn != fMove (the previous doubler was the player on roll
 *                            so the redouble must be a beaver)
 *    Raccoon: fTurn == fMove and/or fCubeOwner != fMove
 *
 *
 */

extern doubletype
DoubleType(const int fDoubled, const int fMove, const int fTurn)
{

    if (fDoubled) {

        /* beaver or raccoon */

        if (fTurn != fMove)
            /* beaver */
            return DT_BEAVER;
        else
            /* raccoon */
            return DT_RACCOON;

    }
    return DT_NORMAL;
}

#else

#define FindnSaveBestMoves FindnSaveBestMovesWithLocking
#define FindBestMove FindBestMoveWithLocking
#define EvaluatePosition EvaluatePositionWithLocking
#define ScoreMove ScoreMoveWithLocking
#define GeneralCubeDecisionE GeneralCubeDecisionEWithLocking
#define GeneralEvaluationE GeneralEvaluationEWithLocking
#define EvaluatePositionCache EvaluatePositionCacheWithLocking
#define FindBestMovePlied FindBestMovePliedWithLocking
#define GeneralEvaluationEPlied GeneralEvaluationEPliedWithLocking
#define EvaluatePositionCubeful3 EvaluatePositionCubeful3WithLocking
#define ScoreMoves ScoreMovesWithLocking
#define ScoreMovesPruned ScoreMovesPrunedWithLocking
#define FindBestMoveInEval FindBestMoveInEvalWithLocking
#define GeneralEvaluationEPliedCubeful GeneralEvaluationEPliedCubefulWithLocking
#define EvaluatePositionCubeful4 EvaluatePositionCubeful4WithLocking
#define CacheAdd CacheAddWithLocking
#define CacheLookup CacheLookupWithLocking

static int EvaluatePositionCache(NNState * nnStates, const TanBoard anBoard, float arOutput[],
                                 cubeinfo * const pci, const evalcontext * pecx, int nPlies, positionclass pc);

static int FindBestMovePlied(int anMove[8], int nDice0, int nDice1,
                             TanBoard anBoard, const cubeinfo * pci,
                             const evalcontext * pec, int nPlies, movefilter aamf[MAX_FILTER_PLIES][MAX_FILTER_PLIES]);

#endif

static int GeneralEvaluationEPlied(NNState * nnStates, float arOutput[NUM_ROLLOUT_OUTPUTS],
                                   const TanBoard anBoard, cubeinfo * const pci, const evalcontext * pec, int nPlies);
static int EvaluatePositionCubeful3(NNState * nnStates, const TanBoard anBoard, float arOutput[NUM_OUTPUTS],
                                    float arCubeful[], const cubeinfo aciCubePos[], int cci, cubeinfo * const pciMove,
                                    const evalcontext * pec, int nPlies, int fTop);

/* Functions that have both locking and non-locking versions below here */

static int ScoreMoves(movelist * pml, const cubeinfo * pci, const evalcontext * pec, int nPlies);
static int ScoreMovesPruned(movelist * pml, const cubeinfo * pci, const evalcontext * pec, unsigned int *bmovesi, unsigned int prune_moves);
/*
   The pruning nets select the best MIN_PRUNE_MOVES +
   floor(log2(number of legal moves)) moves instead of 10 as they used
   to do.  A value of 5 for MIN_PRUNE_MOVES brings a small speed-up
   and, according to the Depreli benchmark, an insignificant strength
   improvement.  Using a lower value causes a measurable degradation
   of play. Using a higher one doesn't significantly improve it.
*/
#define MIN_PRUNE_MOVES 5
#define MAX_PRUNE_MOVES (MIN_PRUNE_MOVES + 11)

static SIMD_AVX_STACKALIGN void
FindBestMoveInEval(NNState * nnStates, int const nDice0, int const nDice1, const TanBoard anBoardIn,
                   TanBoard anBoardOut, cubeinfo * const pci, const evalcontext * pec)
{
    unsigned int i;
    movelist ml;
    positionclass evalClass = CLASS_OVER;
    unsigned int bmovesi[MAX_PRUNE_MOVES];
    unsigned int prune_moves;

    GenerateMoves(&ml, anBoardIn, nDice0, nDice1, FALSE);

    if (ml.cMoves == 0) {
        /* no legal moves */
        return;
    }

    if (ml.cMoves == 1) {
        /* forced move */
        ml.iMoveBest = 0;
        PositionFromKey(anBoardOut, &ml.amMoves[ml.iMoveBest].key);
        return;
    }

    /* LogCube() is floor(log2()) */
    prune_moves = MIN_PRUNE_MOVES + LogCube(ml.cMoves);

    if (ml.cMoves <= prune_moves) {
        ScoreMoves(&ml, pci, pec, 0);
        PositionFromKey(anBoardOut, &ml.amMoves[ml.iMoveBest].key);
        return;
    }

    pci->fMove = !pci->fMove;

    for (i = 0; i < ml.cMoves; i++) {
        positionclass pc;
        SSE_ALIGN(float arInput[NUM_PRUNING_INPUTS]);
        SSE_ALIGN(float arOutput[NUM_OUTPUTS]);
        evalcache ec;
        uint32_t l;
        /* declared volatile to avoid wrong compiler optimization
         * on some gcc systems. Remove with great care. */
        move *const volatile pm = &ml.amMoves[i];

        PositionFromKeySwapped(anBoardOut, &pm->key);

        pc = ClassifyPosition((ConstTanBoard) anBoardOut, VARIATION_STANDARD);
        if (i == 0) {
            if (pc < CLASS_RACE)
                break;
            evalClass = pc;
        } else if (pc != evalClass)
            break;

        CopyKey(pm->key, ec.key);
        ec.nEvalContext = 0;
        if ((l = CacheLookup(&cpEval, &ec, arOutput, NULL)) != CACHEHIT) {
            baseInputs((ConstTanBoard) anBoardOut, arInput);
            {
                neuralnet *nets[] = { &nnpRace, &nnpCrashed, &nnpContact };
                neuralnet *n = nets[pc - CLASS_RACE];
#if defined(USE_SIMD_INSTRUCTIONS)
                (void) nnStates;        /* silence compiler warning */
                NeuralNetEvaluateSSE(n, arInput, arOutput, NULL);
#else
                if (nnStates)
                    nnStates[pc - CLASS_RACE].state = (i == 0) ? NNSTATE_INCREMENTAL : NNSTATE_DONE;
                NeuralNetEvaluate(n, arInput, arOutput, nnStates);
#endif
                if (pc == CLASS_RACE)
                    /* special evaluation of backgammons
                     * overrides net output */
                    EvalRaceBG((ConstTanBoard) anBoardOut, arOutput, VARIATION_STANDARD);

                SanityCheck((ConstTanBoard) anBoardOut, arOutput);
            }
            memcpy(ec.ar, arOutput, sizeof(float) * NUM_OUTPUTS);
            ec.ar[5] = 0.f;
            CacheAdd(&cpEval, &ec, l);
        }
        pm->rScore = UtilityME(arOutput, pci);
        if (i < prune_moves) {
            bmovesi[i] = i;
            if (pm->rScore > ml.amMoves[bmovesi[0]].rScore) {
                bmovesi[i] = bmovesi[0];
                bmovesi[0] = i;
            }
        } else if (pm->rScore < ml.amMoves[bmovesi[0]].rScore) {
            unsigned int m = 0, k;
            bmovesi[0] = i;
            for (k = 1; k < prune_moves; ++k) {
                if (ml.amMoves[bmovesi[k]].rScore > ml.amMoves[bmovesi[m]].rScore) {
                    m = k;
                }
            }
            bmovesi[0] = bmovesi[m];
            bmovesi[m] = i;
        }
    }

    pci->fMove = !pci->fMove;

    if (i == ml.cMoves)
        ScoreMovesPruned(&ml, pci, pec, bmovesi, prune_moves);
    else
        ScoreMoves(&ml, pci, pec, 0);

    PositionFromKey(anBoardOut, &ml.amMoves[ml.iMoveBest].key);
}

static int
EvaluatePositionFull(NNState * nnStates, const TanBoard anBoard, float arOutput[],
                     cubeinfo * const pci, const evalcontext * pec, unsigned int nPlies, positionclass pc)
{
    int i, n0, n1;
    SSE_ALIGN(float arVariationOutput[NUM_OUTPUTS]);
    float rTemp;
    int w;

    if (pc > CLASS_PERFECT && nPlies > 0) {
        /* internal node; recurse */

        TanBoard anBoardNew;
        /* int anMove[ 8 ]; */
        cubeinfo ciOpp;
        int const usePrune = pec->fUsePrune && pec->rNoise == 0.0f && pci->bgv == VARIATION_STANDARD;

        for (i = 0; i < NUM_OUTPUTS; i++)
            arOutput[i] = 0.0;

        /* loop over rolls */

        for (n0 = 1; n0 <= 6; n0++) {
            for (n1 = 1; n1 <= n0; n1++) {
                w = (n0 == n1) ? 1 : 2;

                for (i = 0; i < 25; i++) {
                    anBoardNew[0][i] = anBoard[0][i];
                    anBoardNew[1][i] = anBoard[1][i];
                }

                if (fInterrupt) {
                    errno = EINTR;
                    return -1;
                }

                if (usePrune) {
                    FindBestMoveInEval(nnStates, n0, n1, anBoard, anBoardNew, pci, pec);
                } else {

                    FindBestMovePlied(NULL, n0, n1, anBoardNew, pci, pec, 0, defaultFilters);
                }

                SwapSides(anBoardNew);

                SetCubeInfo(&ciOpp, pci->nCube, pci->fCubeOwner, !pci->fMove,
                            pci->nMatchTo, pci->anScore, pci->fCrawford, pci->fJacoby, pci->fBeavers, pci->bgv);

                /* Evaluate at 0-ply */
                if (EvaluatePositionCache(nnStates, (ConstTanBoard) anBoardNew, arVariationOutput,
                                          &ciOpp, pec, nPlies - 1,
                                          ClassifyPosition((ConstTanBoard) anBoardNew, ciOpp.bgv)))
                    return -1;

                for (i = 0; i < NUM_OUTPUTS; i++)
                    arOutput[i] += w * arVariationOutput[i];
            }

        }

        /* normalize */
        for (i = 0; i < NUM_OUTPUTS; i++)
            arOutput[i] /= 36;

        /* flop eval */
        arOutput[OUTPUT_WIN] = 1.0f - arOutput[OUTPUT_WIN];

        rTemp = arOutput[OUTPUT_WINGAMMON];
        arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_LOSEGAMMON];
        arOutput[OUTPUT_LOSEGAMMON] = rTemp;

        rTemp = arOutput[OUTPUT_WINBACKGAMMON];
        arOutput[OUTPUT_WINBACKGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON];
        arOutput[OUTPUT_LOSEBACKGAMMON] = rTemp;

    } else {
        /* at leaf node; use static evaluation */

        if (acef[pc] (anBoard, arOutput, pci->bgv, nnStates))
            return -1;

        if (pec->rNoise > 0.0f && pc != CLASS_OVER) {
            for (i = 0; i < NUM_OUTPUTS; i++) {
                arOutput[i] += Noise(pec, anBoard, i);
                arOutput[i] = MAX(arOutput[i], 0.0f);
                arOutput[i] = MIN(arOutput[i], 1.0f);
            }
        }

        if (pc > CLASS_GOOD || pec->rNoise > 0.0f)
            /* no sanity check needed for accurate evaluations */
            SanityCheck(anBoard, arOutput);
    }

    return 0;
}


static int
EvaluatePositionCache(NNState * nnStates, const TanBoard anBoard, float arOutput[],
                      cubeinfo * const pci, const evalcontext * pecx, int nPlies, positionclass pc)
{
    evalcache ec;
    uint32_t l;
    /* This should be a part of the code that is called in all
     * time-consuming operations at a relatively steady rate, so is a
     * good choice for a callback function. */
    if (!cCache || pecx->rNoise != 0.0f) {      /* non-deterministic noisy evaluations; cannot cache */
        return EvaluatePositionFull(nnStates, anBoard, arOutput, pci, pecx, nPlies, pc);
    }

    PositionKey(anBoard, &ec.key);

    ec.nEvalContext = EvalKey(pecx, nPlies, pci, FALSE);
    if ((l = CacheLookup(&cEval, &ec, arOutput, NULL)) == CACHEHIT) {
        return 0;
    }

    if (EvaluatePositionFull(nnStates, anBoard, arOutput, pci, pecx, nPlies, pc))
        return -1;

    memcpy(ec.ar, arOutput, sizeof(float) * NUM_OUTPUTS);
    ec.ar[5] = 0.f;
    CacheAdd(&cEval, &ec, l);
    return 0;
}

extern int
EvaluatePosition(NNState * nnStates, const TanBoard anBoard, float arOutput[],
                 cubeinfo * const pci, const evalcontext * pec)
{

    positionclass pc = ClassifyPosition(anBoard, pci->bgv);

    return EvaluatePositionCache(nnStates, anBoard, arOutput, pci, pec ? pec : &ecBasic, pec ? pec->nPlies : 0, pc);
}


extern int
ScoreMove(NNState * nnStates, move * pm, const cubeinfo * pci, const evalcontext * pec, int nPlies)
{
    TanBoard anBoardTemp;
    SSE_ALIGN(float arEval[NUM_ROLLOUT_OUTPUTS]);
    cubeinfo ci;

    PositionFromKeySwapped(anBoardTemp, &pm->key);

    /* swap fMove in cubeinfo */
    memcpy(&ci, pci, sizeof(ci));
    ci.fMove = !ci.fMove;

    if (GeneralEvaluationEPlied(nnStates, arEval, (ConstTanBoard) anBoardTemp, &ci, pec, nPlies))
        return -1;

    InvertEvaluationR(arEval, &ci);

    if (ci.nMatchTo)
        arEval[OUTPUT_CUBEFUL_EQUITY] = mwc2eq(arEval[OUTPUT_CUBEFUL_EQUITY], pci);

    /* Save evaluations */
    memcpy(pm->arEvalMove, arEval, NUM_ROLLOUT_OUTPUTS * sizeof(float));

    /* Save evaluation setup */
    pm->esMove.et = EVAL_EVAL;
    pm->esMove.ec = *pec;
    pm->esMove.ec.nPlies = nPlies;

    /* Score for move:
     * rScore is the primary score (cubeful/cubeless)
     * rScore2 is the secondary score (cubeless) */
    pm->rScore = (pec->fCubeful) ? arEval[OUTPUT_CUBEFUL_EQUITY] : arEval[OUTPUT_EQUITY];
    pm->rScore2 = arEval[OUTPUT_EQUITY];

    return 0;
}

static int
ScoreMoves(movelist * pml, const cubeinfo * pci, const evalcontext * pec, int nPlies)
{
    unsigned int i;
    int r = 0;                  /* return value */
    NNState *nnStates = MT_Get_nnState();

    pml->rBestScore = -99999.9f;

    if (nPlies == 0) {
        /* start incremental evaluations */
        nnStates[0].state = nnStates[1].state = nnStates[2].state = NNSTATE_INCREMENTAL;
    }


    for (i = 0; i < pml->cMoves; i++) {
        if (ScoreMove(nnStates, pml->amMoves + i, pci, pec, nPlies) < 0) {
            r = -1;
            break;
        }

        if ((pml->amMoves[i].rScore > pml->rBestScore) || ((pml->amMoves[i].rScore == pml->rBestScore)
                                                           && (pml->amMoves[i].rScore2 >
                                                               pml->amMoves[pml->iMoveBest].rScore2))) {
            pml->iMoveBest = i;
            pml->rBestScore = pml->amMoves[i].rScore;
        }
    }

    if (nPlies == 0) {
        /* reset to none */

        nnStates[0].state = nnStates[1].state = nnStates[2].state = NNSTATE_NONE;
    }

    return r;
}

static int
ScoreMovesPruned(movelist * pml, const cubeinfo * pci, const evalcontext * pec, unsigned int *bmovesi, unsigned int prune_moves)
{
    unsigned int i, j;
    int r = 0;                  /* return value */
    NNState *nnStates = MT_Get_nnState();

    pml->rBestScore = -99999.9f;

    /* start incremental evaluations */
    nnStates[0].state = nnStates[1].state = nnStates[2].state = NNSTATE_INCREMENTAL;

    for (j = 0; j < prune_moves; j++) {

        i = bmovesi[j];

        if (ScoreMove(nnStates, pml->amMoves + i, pci, pec, 0) < 0) {
            r = -1;
            break;
        }

        if ((pml->amMoves[i].rScore > pml->rBestScore) || ((pml->amMoves[i].rScore == pml->rBestScore)
                                                           && (pml->amMoves[i].rScore2 >
                                                               pml->amMoves[pml->iMoveBest].rScore2))) {
            pml->iMoveBest = i;
            pml->rBestScore = pml->amMoves[i].rScore;
        }
    }

    nnStates[0].state = nnStates[1].state = nnStates[2].state = NNSTATE_NONE;

    return r;
}

static movefilter NullFilter = { 0, 0, 0.0 };

static int
FindBestMovePlied(int anMove[8], int nDice0, int nDice1,
                  TanBoard anBoard,
                  const cubeinfo * pci, const evalcontext * pec, int nPlies,
                  movefilter aamf[MAX_FILTER_PLIES][MAX_FILTER_PLIES])
{

    evalcontext ec;
    movelist ml;
    unsigned int i;

    memcpy(&ec, pec, sizeof(evalcontext));
    ec.nPlies = nPlies;

    if (anMove)
        for (i = 0; i < 8; ++i)
            anMove[i] = -1;

    if (FindnSaveBestMoves(&ml, nDice0, nDice1, (ConstTanBoard) anBoard, NULL, 0.0f, pci, &ec, aamf) < 0) {
        free(ml.amMoves);
        return -1;
    }

    if (anMove) {
        for (i = 0; i < ml.cMaxMoves * 2; i++)
            anMove[i] = ml.amMoves[ml.iMoveBest].anMove[i];
    }

    if (ml.cMoves)
        PositionFromKey(anBoard, &ml.amMoves[ml.iMoveBest].key);

    free(ml.amMoves);

    return ml.cMaxMoves * 2;
}


extern
    int
FindBestMove(int anMove[8], int nDice0, int nDice1,
             TanBoard anBoard, const cubeinfo * pci, evalcontext * pec,
             movefilter aamf[MAX_FILTER_PLIES][MAX_FILTER_PLIES])
{

    return FindBestMovePlied(anMove, nDice0, nDice1, anBoard, pci, pec ? pec : &ecBasic, pec ? pec->nPlies : 0, aamf);
}

extern int
FindnSaveBestMoves(movelist * pml, int nDice0, int nDice1, const TanBoard anBoard, positionkey * keyMove, const
                   float rThr, const cubeinfo * pci, const evalcontext * pec,
                   movefilter aamf[MAX_FILTER_PLIES][MAX_FILTER_PLIES])
{

    /* Find best moves. 
     * Ensure that keyMove is evaluated at the deepest ply. */

    unsigned int i;
    unsigned int nMoves, iPly;
    move *pm;
    movefilter *mFilters;
    unsigned int nMaxPly = 0;
    unsigned int cOldMoves;

    /* Find all moves -- note that pml contains internal pointers to static
     * data, so we can't call GenerateMoves again (or anything that calls
     * it, such as ScoreMoves at more than 0 plies) until we have saved
     * the moves we want to keep in amCandidates. */
    GenerateMoves(pml, anBoard, nDice0, nDice1, FALSE);

    if (pml->cMoves == 0) {
        /* no legal moves */
        pml->amMoves = NULL;
        return 0;
    }

    /* Save moves */
    pm = (move *) malloc(pml->cMoves * sizeof(move));
    memcpy(pm, pml->amMoves, pml->cMoves * sizeof(move));
    pml->amMoves = pm;
    nMoves = pml->cMoves;

    mFilters = (pec->nPlies > 0 && pec->nPlies <= MAX_FILTER_PLIES) ?
        aamf[pec->nPlies - 1] : aamf[MAX_FILTER_PLIES - 1];

    for (iPly = 0; iPly < pec->nPlies; iPly++) {

        movefilter *mFilter = (iPly < MAX_FILTER_PLIES) ? &mFilters[iPly] : &NullFilter;

        unsigned int k;

        if (mFilter->Accept < 0) {
            continue;
        }

        if (ScoreMoves(pml, pci, pec, iPly) < 0) {
            free(pm);
            pml->cMoves = 0;
            pml->amMoves = NULL;
            return -1;
        }

        qsort(pml->amMoves, pml->cMoves, sizeof(move), (cfunc) CompareMoves);
        pml->iMoveBest = 0;

        k = pml->cMoves;
        /* we check for mFilter->Accept < 0 above */
        pml->cMoves = MIN((unsigned int) mFilter->Accept, pml->cMoves);

        {
            unsigned int limit = MIN(k, pml->cMoves + mFilter->Extra);

            for ( /**/; pml->cMoves < limit; ++pml->cMoves) {
                if (pml->amMoves[pml->cMoves].rScore < pml->amMoves[0].rScore - mFilter->Threshold) {
                    break;
                }
            }
        }

        nMaxPly = iPly;

        if (pml->cMoves == 1 && mFilter->Accept != 1)
            /* if there is only one move to evaluate there is no need to continue */
            goto finished;


    }

    /* evaluate moves on top ply */

    if (ScoreMoves(pml, pci, pec, pec->nPlies) < 0) {
        free(pm);
        pml->cMoves = 0;
        pml->amMoves = NULL;
        return -1;
    }

    nMaxPly = pec->nPlies;

    /* Resort the moves, in case the new evaluation reordered them. */
    qsort(pml->amMoves, pml->cMoves, sizeof(move), (cfunc) CompareMoves);
    pml->iMoveBest = 0;

    /* set the proper size of the movelist */

  finished:

    cOldMoves = pml->cMoves;
    pml->cMoves = nMoves;

    /* Make sure that keyMove and top move are both  
     * evaluated at the deepest ply. */
    if (keyMove) {

        int fResort = FALSE;

        for (i = 0; i < pml->cMoves; i++)
            if (EqualKeys((*keyMove), pml->amMoves[i].key)) {

                /* ensure top move is evaluted at deepest ply */

                if (pml->amMoves[i].esMove.ec.nPlies < nMaxPly) {
                    ScoreMove(NULL, pml->amMoves + i, pci, pec, nMaxPly);
                    fResort = TRUE;
                }

                if ((fabsf(pml->amMoves[i].rScore - pml->amMoves[0].rScore) > rThr) && (nMaxPly < pec->nPlies)) {

                    /* this is en error/blunder: re-analyse at top-ply */

                    ScoreMove(NULL, pml->amMoves, pci, pec, pec->nPlies);
                    ScoreMove(NULL, pml->amMoves + i, pci, pec, pec->nPlies);
                    cOldMoves = 1;      /* only one move scored at deepest ply */
                    fResort = TRUE;

                }

                /* move it up to the other moves evaluated on nMaxPly */

                if (fResort && pec->nPlies) {
                    move m;
                    unsigned int j;

                    memcpy(&m, pml->amMoves + i, sizeof m);

                    for (j = i - 1; j >= cOldMoves; --j)
                        memcpy(pml->amMoves + j + 1, pml->amMoves + j, sizeof(move));

                    memcpy(pml->amMoves + cOldMoves, &m, sizeof(m));

                    /* reorder moves evaluated on nMaxPly */

                    qsort(pml->amMoves, cOldMoves + 1, sizeof(move), (cfunc) CompareMoves);

                }
                break;
            }
    }

    return 0;

}

extern int
GeneralCubeDecisionE(float aarOutput[2][NUM_ROLLOUT_OUTPUTS],
                     const TanBoard anBoard,
                     cubeinfo * const pci, const evalcontext * pec, const evalsetup * UNUSED(pes))
{

    SSE_ALIGN(float arOutput[NUM_OUTPUTS]);
    cubeinfo aciCubePos[2];
    float arCubeful[2];
    int i, j;


    /* Setup cube for "no double" and "double, take" */

    memcpy(&aciCubePos[0], pci, sizeof(cubeinfo));
    memcpy(&aciCubePos[1], pci, sizeof(cubeinfo));
    aciCubePos[1].fCubeOwner = !aciCubePos[1].fMove;
    aciCubePos[1].nCube *= 2;

    if (EvaluatePositionCubeful3(NULL, anBoard, arOutput, arCubeful, aciCubePos, 2, pci, pec, pec->nPlies, TRUE))
        return -1;


    /* Scale double-take equity */
    if (!pci->nMatchTo)
        arCubeful[1] *= 2.0f;

    for (i = 0; i < 2; i++) {

        /* copy cubeless winning chances */
        for (j = 0; j < NUM_OUTPUTS; j++)
            aarOutput[i][j] = arOutput[j];

        /* equity */

        aarOutput[i][OUTPUT_EQUITY] = UtilityME(arOutput, &aciCubePos[i]);

        aarOutput[i][OUTPUT_CUBEFUL_EQUITY] = arCubeful[i];

    }

    return 0;

}

extern int
GeneralEvaluationE(float arOutput[NUM_ROLLOUT_OUTPUTS],
                   const TanBoard anBoard, cubeinfo * const pci, const evalcontext * pec)
{

    return GeneralEvaluationEPlied(NULL, arOutput, anBoard, pci, pec, pec->nPlies);

}


static int
GeneralEvaluationEPliedCubeful(NNState * nnStates, float arOutput[NUM_ROLLOUT_OUTPUTS],
                               const TanBoard anBoard, cubeinfo * const pci, const evalcontext * pec, int nPlies)
{

    float rCubeful;

    if (EvaluatePositionCubeful3(nnStates, anBoard, arOutput, &rCubeful, pci, 1, pci, pec, nPlies, FALSE))
        return -1;

    arOutput[OUTPUT_EQUITY] = UtilityME(arOutput, pci);
    arOutput[OUTPUT_CUBEFUL_EQUITY] = rCubeful;

    return 0;

}

extern int
GeneralEvaluationEPlied(NNState * nnStates, float arOutput[NUM_ROLLOUT_OUTPUTS],
                        const TanBoard anBoard, cubeinfo * const pci, const evalcontext * pec, int nPlies)
{

    if (pec->fCubeful) {

        if (GeneralEvaluationEPliedCubeful(nnStates, arOutput, anBoard, pci, pec, nPlies))
            return -1;

    } else {
        if (EvaluatePositionCache(nnStates, anBoard, arOutput, pci, pec, nPlies, ClassifyPosition(anBoard, pci->bgv)))
            return -1;

        arOutput[OUTPUT_EQUITY] = UtilityME(arOutput, pci);
        arOutput[OUTPUT_CUBEFUL_EQUITY] = 0.0f;

    }

    return 0;

}

static int
EvaluatePositionCubeful4(NNState * nnStates, const TanBoard anBoard,
                         float arOutput[NUM_OUTPUTS],
                         float arCubeful[],
                         const cubeinfo aciCubePos[], int cci,
                         cubeinfo * const pciMove, const evalcontext * pec, unsigned int nPlies, int fTop)
{


    /* calculate cubeful equity */

    int i, ici;
    positionclass pc;
    float r;
    SSE_ALIGN(float ar[NUM_OUTPUTS]);
    float arEquity[4];
    float rCubeX;

    cubeinfo ciMoveOpp;

    float *arCf = (float *) g_alloca(2 * cci * sizeof(float));
    float *arCfTemp = (float *) g_alloca(2 * cci * sizeof(float));
    cubeinfo *aci = (cubeinfo *) g_alloca(2 * cci * sizeof(cubeinfo));

    int w;
    int n0, n1;

    pc = ClassifyPosition(anBoard, pciMove->bgv);

    if (pc > CLASS_OVER && nPlies > 0 && !(pc <= CLASS_PERFECT && !pciMove->nMatchTo)) {
        /* internal node; recurse */

        TanBoard anBoardNew;

        int const usePrune = pec->fUsePrune && pec->rNoise == 0.0f && pciMove->bgv == VARIATION_STANDARD;

        for (i = 0; i < NUM_OUTPUTS; i++)
            arOutput[i] = 0.0;

        for (i = 0; i < 2 * cci; i++)
            arCf[i] = 0.0;

        /* construct next level cube positions */

        MakeCubePos(aciCubePos, cci, fTop, aci, TRUE);

        /* loop over rolls */

        for (n0 = 1; n0 <= 6; n0++) {
            for (n1 = 1; n1 <= n0; n1++) {
                w = (n0 == n1) ? 1 : 2;

                for (i = 0; i < 25; i++) {
                    anBoardNew[0][i] = anBoard[0][i];
                    anBoardNew[1][i] = anBoard[1][i];
                }

                if (fInterrupt) {
                    errno = EINTR;
                    return -1;
                }

                if (usePrune) {
                    FindBestMoveInEval(nnStates, n0, n1, anBoard, anBoardNew, pciMove, pec);
                } else {

                    FindBestMovePlied(NULL, n0, n1, anBoardNew, pciMove, pec, 0, defaultFilters);
                }

                SwapSides(anBoardNew);

                SetCubeInfo(&ciMoveOpp,
                            pciMove->nCube, pciMove->fCubeOwner,
                            !pciMove->fMove, pciMove->nMatchTo,
                            pciMove->anScore, pciMove->fCrawford, pciMove->fJacoby, pciMove->fBeavers, pciMove->bgv);

                /* Evaluate at 0-ply */
                if (EvaluatePositionCubeful3(nnStates, (ConstTanBoard) anBoardNew,
                                             ar, arCfTemp, aci, 2 * cci, &ciMoveOpp, pec, nPlies - 1, FALSE))
                    return -1;

                /* Sum up cubeless winning chances and cubeful equities */

                for (i = 0; i < NUM_OUTPUTS; i++)
                    arOutput[i] += w * ar[i];
                for (i = 0; i < 2 * cci; i++)
                    arCf[i] += w * arCfTemp[i];

            }

        }

        /* Flip evals */
#define sumW 36

        arOutput[OUTPUT_WIN] = 1.0f - arOutput[OUTPUT_WIN] / sumW;

        r = arOutput[OUTPUT_WINGAMMON] / sumW;
        arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_LOSEGAMMON] / sumW;
        arOutput[OUTPUT_LOSEGAMMON] = r;

        r = arOutput[OUTPUT_WINBACKGAMMON] / sumW;
        arOutput[OUTPUT_WINBACKGAMMON] = arOutput[OUTPUT_LOSEBACKGAMMON] / sumW;
        arOutput[OUTPUT_LOSEBACKGAMMON] = r;

        for (i = 0; i < 2 * cci; i++)
            if (pciMove->nMatchTo)
                arCf[i] = 1.0f - arCf[i] / sumW;
            else
                arCf[i] = -arCf[i] / sumW;
#undef sumW

        /* invert fMove */
        /* Remember than fMove was inverted in the call to MakeCubePos */

        for (i = 0; i < 2 * cci; i++)
            aci[i].fMove = !aci[i].fMove;

        /* get cubeful equities */

        GetECF3(arCubeful, cci, arCf, aci);

    } else {
        /* at leaf node; use static evaluation */

        if (pc == CLASS_HYPERGAMMON1 || pc == CLASS_HYPERGAMMON2 || pc == CLASS_HYPERGAMMON3) {

            bearoffcontext *pbc = apbcHyper[pc - CLASS_HYPERGAMMON1];
            unsigned int nUs, nThem, iPos;
            unsigned int n;

            if (!pbc)
                return -1;

            nUs = PositionBearoff(anBoard[1], pbc->nPoints, pbc->nChequers);
            nThem = PositionBearoff(anBoard[0], pbc->nPoints, pbc->nChequers);
            n = Combination(pbc->nPoints + pbc->nChequers, pbc->nPoints);
            iPos = nUs * n + nThem;

            if (BearoffHyper(apbcHyper[pc - CLASS_HYPERGAMMON1], iPos, arOutput, arEquity))
                return -1;

        } else if (pc > CLASS_OVER && pc <= CLASS_PERFECT /* && ! pciMove->nMatchTo */ ) {

            if (EvaluatePerfectCubeful(anBoard, arEquity, pciMove->bgv)) {
                return -1;
            }

            arOutput[OUTPUT_WIN] = (arEquity[0] + 1.0f) / 2.0f;
            arOutput[OUTPUT_WINGAMMON] = arOutput[OUTPUT_WINBACKGAMMON] = arOutput[OUTPUT_LOSEGAMMON] =
                arOutput[OUTPUT_LOSEBACKGAMMON] = 0.0;

        } else {

            /* evaluate with neural net */

            if (EvaluatePosition(nnStates, anBoard, arOutput, pciMove, NULL))
                return -1;

            if (pec->rNoise > 0.0f && pc != CLASS_OVER) {
                for (i = 0; i < NUM_OUTPUTS; i++) {
                    arOutput[i] += Noise(pec, anBoard, i);
                    arOutput[i] = MAX(arOutput[i], 0.0f);
                    arOutput[i] = MIN(arOutput[i], 1.0f);
                }
            }

            if (pc > CLASS_GOOD || pec->rNoise > 0.0f)
                /* no sanity check needed for accurate evaluations */
                SanityCheck(anBoard, arOutput);

        }

        /* Calculate cube efficiency */

        rCubeX = EvalEfficiency(anBoard, pc);

        /* Build all possible cube positions */

        MakeCubePos(aciCubePos, cci, fTop, aci, FALSE);

        /* Calculate cubeful equity for each possible cube position */

        for (ici = 0; ici < 2 * cci; ici++)
            if (aci[ici].nCube > 0) {
                /* cube available */

                if (!aci[ici].nMatchTo) {

                    /* money play */

                    switch (pc) {
                    case CLASS_HYPERGAMMON1:
                    case CLASS_HYPERGAMMON2:
                    case CLASS_HYPERGAMMON3:
                        /* exact bearoff equities & contact */

                        arCf[ici] = CFHYPER(arEquity, &aci[ici]);
                        break;

                    case CLASS_BEAROFF2:
                    case CLASS_BEAROFF_TS:
                        /* exact bearoff equities */

                        arCf[ici] = CFMONEY(arEquity, &aci[ici]);
                        break;

                    case CLASS_OVER:
                    case CLASS_RACE:
                    case CLASS_CRASHED:
                    case CLASS_CONTACT:
                    case CLASS_BEAROFF1:
                    case CLASS_BEAROFF_OS:
                        /* approximate using Janowski's formulae */

                        arCf[ici] = Cl2CfMoney(arOutput, &aci[ici], rCubeX);
                        break;

                    }

                } else {

                    float rCl, rCf, rCfMoney;
                    float X = rCubeX;
                    cubeinfo ciMoney;

                    /* match play */

                    switch (pc) {
                    case CLASS_HYPERGAMMON1:
                    case CLASS_HYPERGAMMON2:
                    case CLASS_HYPERGAMMON3:
                        /* use exact money equities to guess cube efficiency */

                        SetCubeInfoMoney(&ciMoney, 1, aci[ici].fCubeOwner, aci[ici].fMove, FALSE, FALSE, aci[ici].bgv);

                        rCl = Utility(arOutput, &ciMoney);
                        rCubeX = 1.0;
                        rCf = Cl2CfMoney(arOutput, &ciMoney, rCubeX);
                        rCfMoney = CFHYPER(arEquity, &ciMoney);

                        if (fabsf(rCl - rCf) > 0.0001f)
                            rCubeX = (rCfMoney - rCl) / (rCf - rCl);

                        arCf[ici] = Cl2CfMatch(arOutput, &aci[ici], rCubeX);

                        rCubeX = X;

                        break;

                    case CLASS_BEAROFF2:
                    case CLASS_BEAROFF_TS:
                        /* use exact money equities to guess cube efficiency */

                        SetCubeInfoMoney(&ciMoney, 1, aci[ici].fCubeOwner, aci[ici].fMove, FALSE, FALSE, aci[ici].bgv);

                        rCl = arEquity[0];
                        rCubeX = 1.0;
                        rCf = Cl2CfMoney(arOutput, &ciMoney, rCubeX);
                        rCfMoney = CFMONEY(arEquity, &ciMoney);

                        if (fabsf(rCl - rCf) > 0.0001f)
                            rCubeX = (rCfMoney - rCl) / (rCf - rCl);
                        else
                            rCubeX = X;

                        /* fabs(...) > 0.0001 above is not enough. We still get some
                         * nutty values for rCubeX and need more sanity checking */

                        if (rCubeX < 0.0f)
                            rCubeX = 0.0f;
                        if (rCubeX > X)
                            rCubeX = X;

                        arCf[ici] = Cl2CfMatch(arOutput, &aci[ici], rCubeX);

                        rCubeX = X;

                        break;

                    case CLASS_OVER:
                    case CLASS_RACE:
                    case CLASS_CRASHED:
                    case CLASS_CONTACT:
                    case CLASS_BEAROFF1:
                    case CLASS_BEAROFF_OS:
                        /* approximate using Joern's generalisation of 
                         * Janowski's formulae */

                        arCf[ici] = Cl2CfMatch(arOutput, &aci[ici], rCubeX);
                        break;

                    }

                }

            }


        /* find optimal of "no double" and "double" */

        GetECF3(arCubeful, cci, arCf, aci);

    }

    return 0;

}

/* EvaluatePositionCubeful3 is now just a wrapper for ....Cubeful4, which
 * first checks the cache, and then calls ...Cubeful3 */

extern int
EvaluatePositionCubeful3(NNState * nnStates, const TanBoard anBoard,
                         float arOutput[NUM_OUTPUTS],
                         float arCubeful[],
                         const cubeinfo aciCubePos[], int cci,
                         cubeinfo * const pciMove, const evalcontext * pec, int nPlies, int fTop)
{

    int ici;
    int fAll = TRUE;
    evalcache ec;

    if (!cCache || pec->rNoise != 0.0f)
        /* non-deterministic evaluation; never cache */
    {
        return EvaluatePositionCubeful4(nnStates, anBoard, arOutput, arCubeful,
                                        aciCubePos, cci, pciMove, pec, nPlies, fTop);
    }

    PositionKey(anBoard, &ec.key);

    /* check cache for existence for earlier calculation */

    fAll = !fTop;               /* FIXME: fTop should be a part of EvalKey */

    for (ici = 0; ici < cci && fAll; ++ici) {

        if (aciCubePos[ici].nCube < 0) {
            continue;
        }

        ec.nEvalContext = EvalKey(pec, nPlies, &aciCubePos[ici], TRUE);

        if (CacheLookup(&cEval, &ec, arOutput, arCubeful + ici) != CACHEHIT) {
            fAll = FALSE;
        }
    }

    /* get equities */

    if (!fAll) {

        /* cache miss */
        if (EvaluatePositionCubeful4(nnStates, anBoard, arOutput, arCubeful,
                                     aciCubePos, cci, pciMove, pec, nPlies, fTop))
            return -1;

        /* add to cache */

        if (!fTop) {

            for (ici = 0; ici < cci; ++ici) {
                if (aciCubePos[ici].nCube < 0)
                    continue;

                memcpy(ec.ar, arOutput, sizeof(float) * NUM_OUTPUTS);
                ec.ar[5] = arCubeful[ici];      /* Cubeful equity stored in slot 5 */
                ec.nEvalContext = EvalKey(pec, nPlies, &aciCubePos[ici], TRUE);

                CacheAdd(&cEval, &ec, GetHashKey(cEval.hashMask, &ec));

            }
        }
    }

    return 0;

}