1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136
|
/*
* backend.c -- Common back end for X and Windows NT versions of
*
* Copyright 1991 by Digital Equipment Corporation, Maynard,
* Massachusetts.
*
* Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free
* Software Foundation, Inc.
*
* Enhancements Copyright 2005 Alessandro Scotti
*
* The following terms apply to Digital Equipment Corporation's copyright
* interest in XBoard:
* ------------------------------------------------------------------------
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of Digital not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
* ------------------------------------------------------------------------
*
* The following terms apply to the enhanced version of XBoard
* distributed by the Free Software Foundation:
* ------------------------------------------------------------------------
*
* GNU XBoard is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* GNU XBoard 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, see http://www.gnu.org/licenses/. *
*
*------------------------------------------------------------------------
** See the file ChangeLog for a revision history. */
/* [AS] Also useful here for debugging */
#ifdef WIN32
#include <windows.h>
int flock(int f, int code);
# define LOCK_EX 2
# define SLASH '\\'
# ifdef ARC_64BIT
# define EGBB_NAME "egbbdll64.dll"
# else
# define EGBB_NAME "egbbdll.dll"
# endif
#else
# include <sys/file.h>
# define SLASH '/'
# include <dlfcn.h>
# ifdef ARC_64BIT
# define EGBB_NAME "egbbso64.so"
# else
# define EGBB_NAME "egbbso.so"
# endif
// kludge to allow Windows code in back-end by converting it to corresponding Linux code
# define CDECL
# define HMODULE void *
# define LoadLibrary(x) dlopen(x, RTLD_LAZY)
# define GetProcAddress dlsym
#endif
#include "config.h"
#include <assert.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <math.h>
#include <ctype.h>
#if STDC_HEADERS
# include <stdlib.h>
# include <string.h>
# include <stdarg.h>
#else /* not STDC_HEADERS */
# if HAVE_STRING_H
# include <string.h>
# else /* not HAVE_STRING_H */
# include <strings.h>
# endif /* not HAVE_STRING_H */
#endif /* not STDC_HEADERS */
#if HAVE_SYS_FCNTL_H
# include <sys/fcntl.h>
#else /* not HAVE_SYS_FCNTL_H */
# if HAVE_FCNTL_H
# include <fcntl.h>
# endif /* HAVE_FCNTL_H */
#endif /* not HAVE_SYS_FCNTL_H */
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#if defined(_amigados) && !defined(__GNUC__)
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
extern int gettimeofday(struct timeval *, struct timezone *);
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "common.h"
#include "frontend.h"
#include "backend.h"
#include "parser.h"
#include "moves.h"
#if ZIPPY
# include "zippy.h"
#endif
#include "backendz.h"
#include "evalgraph.h"
#include "engineoutput.h"
#include "gettext.h"
#ifdef ENABLE_NLS
# define _(s) gettext (s)
# define N_(s) gettext_noop (s)
# define T_(s) gettext(s)
#else
# ifdef WIN32
# define _(s) T_(s)
# define N_(s) s
# else
# define _(s) (s)
# define N_(s) s
# define T_(s) s
# endif
#endif
int establish P((void));
void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void SendToICS P((char *s));
void SendToICSDelayed P((char *s, long msdelay));
void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
void HandleMachineMove P((char *message, ChessProgramState *cps));
int AutoPlayOneMove P((void));
int LoadGameOneMove P((ChessMove readAhead));
int LoadGameFromFile P((char *filename, int n, char *title, int useList));
int LoadPositionFromFile P((char *filename, int n, char *title));
int SavePositionToFile P((char *filename));
void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
void ShowMove P((int fromX, int fromY, int toX, int toY));
int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
/*char*/int promoChar));
void BackwardInner P((int target));
void ForwardInner P((int target));
int Adjudicate P((ChessProgramState *cps));
void GameEnds P((ChessMove result, char *resultDetails, int whosays));
void EditPositionDone P((Boolean fakeRights));
void PrintOpponents P((FILE *fp));
void PrintPosition P((FILE *fp, int move));
void SendToProgram P((char *message, ChessProgramState *cps));
void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
char *buf, int count, int error));
void SendTimeControl P((ChessProgramState *cps,
int mps, long tc, int inc, int sd, int st));
char *TimeControlTagValue P((void));
void Attention P((ChessProgramState *cps));
void FeedMovesToProgram P((ChessProgramState *cps, int upto));
int ResurrectChessProgram P((void));
void DisplayComment P((int moveNumber, char *text));
void DisplayMove P((int moveNumber));
void ParseGameHistory P((char *game));
void ParseBoard12 P((char *string));
void KeepAlive P((void));
void StartClocks P((void));
void SwitchClocks P((int nr));
void StopClocks P((void));
void ResetClocks P((void));
char *PGNDate P((void));
void SetGameInfo P((void));
int RegisterMove P((void));
void MakeRegisteredMove P((void));
void TruncateGame P((void));
int looking_at P((char *, int *, char *));
void CopyPlayerNameIntoFileName P((char **, char *));
char *SavePart P((char *));
int SaveGameOldStyle P((FILE *));
int SaveGamePGN P((FILE *));
int CheckFlags P((void));
long NextTickLength P((long));
void CheckTimeControl P((void));
void show_bytes P((FILE *, char *, int));
int string_to_rating P((char *str));
void ParseFeatures P((char* args, ChessProgramState *cps));
void InitBackEnd3 P((void));
void FeatureDone P((ChessProgramState* cps, int val));
void InitChessProgram P((ChessProgramState *cps, int setup));
void OutputKibitz(int window, char *text);
int PerpetualChase(int first, int last);
int EngineOutputIsUp();
void InitDrawingSizes(int x, int y);
void NextMatchGame P((void));
int NextTourneyGame P((int nr, int *swap));
int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
FILE *WriteTourneyFile P((char *results, FILE *f));
void DisplayTwoMachinesTitle P(());
static void ExcludeClick P((int index));
void ToggleSecond P((void));
void PauseEngine P((ChessProgramState *cps));
static int NonStandardBoardSize P((VariantClass v, int w, int h, int s));
#ifdef WIN32
extern void ConsoleCreate();
#endif
ChessProgramState *WhitePlayer();
int VerifyDisplayMode P(());
char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
void ics_update_width P((int new_width));
extern char installDir[MSG_SIZ];
VariantClass startVariant; /* [HGM] nicks: initial variant */
Boolean abortMatch;
int deadRanks;
extern int tinyLayout, smallLayout;
ChessProgramStats programStats;
char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
int endPV = -1;
static int exiting = 0; /* [HGM] moved to top */
static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
int partnerHighlight[2];
Boolean partnerBoardValid = 0;
char partnerStatus[MSG_SIZ];
Boolean partnerUp;
Boolean originalFlip;
Boolean twoBoards = 0;
char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
int opponentKibitzes;
int lastSavedGame; /* [HGM] save: ID of game */
char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
extern int chatCount;
int chattingPartner;
char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
char legal[BOARD_RANKS][BOARD_FILES]; /* [HGM] legal target squares */
char lastMsg[MSG_SIZ];
char lastTalker[MSG_SIZ];
ChessSquare pieceSweep = EmptySquare;
ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
int promoDefaultAltered;
int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
static int initPing = -1;
int border; /* [HGM] width of board rim, needed to size seek graph */
char bestMove[MSG_SIZ], avoidMove[MSG_SIZ];
int solvingTime, totalTime;
/* States for ics_getting_history */
#define H_FALSE 0
#define H_REQUESTED 1
#define H_GOT_REQ_HEADER 2
#define H_GOT_UNREQ_HEADER 3
#define H_GETTING_MOVES 4
#define H_GOT_UNWANTED_HEADER 5
/* whosays values for GameEnds */
#define GE_ICS 0
#define GE_ENGINE 1
#define GE_PLAYER 2
#define GE_FILE 3
#define GE_XBOARD 4
#define GE_ENGINE1 5
#define GE_ENGINE2 6
/* Maximum number of games in a cmail message */
#define CMAIL_MAX_GAMES 20
/* Different types of move when calling RegisterMove */
#define CMAIL_MOVE 0
#define CMAIL_RESIGN 1
#define CMAIL_DRAW 2
#define CMAIL_ACCEPT 3
/* Different types of result to remember for each game */
#define CMAIL_NOT_RESULT 0
#define CMAIL_OLD_RESULT 1
#define CMAIL_NEW_RESULT 2
/* Telnet protocol constants */
#define TN_WILL 0373
#define TN_WONT 0374
#define TN_DO 0375
#define TN_DONT 0376
#define TN_IAC 0377
#define TN_ECHO 0001
#define TN_SGA 0003
#define TN_PORT 23
char*
safeStrCpy (char *dst, const char *src, size_t count)
{ // [HGM] made safe
int i;
assert( dst != NULL );
assert( src != NULL );
assert( count > 0 );
for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
if( i == count && dst[count-1] != NULLCHAR)
{
dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
if(appData.debugMode)
fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
}
return dst;
}
/* Some compiler can't cast u64 to double
* This function do the job for us:
* We use the highest bit for cast, this only
* works if the highest bit is not
* in use (This should not happen)
*
* We used this for all compiler
*/
double
u64ToDouble (u64 value)
{
double r;
u64 tmp = value & u64Const(0x7fffffffffffffff);
r = (double)(s64)tmp;
if (value & u64Const(0x8000000000000000))
r += 9.2233720368547758080e18; /* 2^63 */
return r;
}
/* Fake up flags for now, as we aren't keeping track of castling
availability yet. [HGM] Change of logic: the flag now only
indicates the type of castlings allowed by the rule of the game.
The actual rights themselves are maintained in the array
castlingRights, as part of the game history, and are not probed
by this function.
*/
int
PosFlags (int index)
{
int flags = F_ALL_CASTLE_OK;
if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
switch (gameInfo.variant) {
case VariantSuicide:
flags &= ~F_ALL_CASTLE_OK;
case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
flags |= F_IGNORE_CHECK;
case VariantLosers:
flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
break;
case VariantAtomic:
flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
break;
case VariantKriegspiel:
flags |= F_KRIEGSPIEL_CAPTURE;
break;
case VariantCapaRandom:
case VariantFischeRandom:
flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
case VariantNoCastle:
case VariantShatranj:
case VariantCourier:
case VariantMakruk:
case VariantASEAN:
case VariantGrand:
flags &= ~F_ALL_CASTLE_OK;
break;
case VariantChu:
case VariantChuChess:
case VariantLion:
flags |= F_NULL_MOVE;
break;
default:
break;
}
if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
return flags;
}
FILE *gameFileFP, *debugFP, *serverFP;
char *currentDebugFile; // [HGM] debug split: to remember name
/*
[AS] Note: sometimes, the sscanf() function is used to parse the input
into a fixed-size buffer. Because of this, we must be prepared to
receive strings as long as the size of the input buffer, which is currently
set to 4K for Windows and 8K for the rest.
So, we must either allocate sufficiently large buffers here, or
reduce the size of the input buffer in the input reading part.
*/
char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
char thinkOutput1[MSG_SIZ*10];
char promoRestrict[MSG_SIZ];
ChessProgramState first, second, pairing;
/* premove variables */
int premoveToX = 0;
int premoveToY = 0;
int premoveFromX = 0;
int premoveFromY = 0;
int premovePromoChar = 0;
int gotPremove = 0;
Boolean alarmSounded;
/* end premove variables */
char *ics_prefix = "$";
enum ICS_TYPE ics_type = ICS_GENERIC;
int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
int pauseExamForwardMostMove = 0;
int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
int whiteFlag = FALSE, blackFlag = FALSE;
int userOfferedDraw = FALSE;
int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
int cmailMoveType[CMAIL_MAX_GAMES];
long ics_clock_paused = 0;
ProcRef icsPR = NoProc, cmailPR = NoProc;
InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
GameMode gameMode = BeginningOfGame;
char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
int hiddenThinkOutputState = 0; /* [AS] */
int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
int adjudicateLossPlies = 6;
char white_holding[64], black_holding[64];
TimeMark lastNodeCountTime;
long lastNodeCount=0;
int shiftKey, controlKey; // [HGM] set by mouse handler
int have_sent_ICS_logon = 0;
int movesPerSession;
int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
Boolean adjustedClock;
long timeControl_2; /* [AS] Allow separate time controls */
char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
long timeRemaining[2][MAX_MOVES];
int matchGame = 0, nextGame = 0, roundNr = 0;
Boolean waitingForGame = FALSE, startingEngine = FALSE;
TimeMark programStartTime, pauseStart;
char ics_handle[MSG_SIZ];
int have_set_title = 0;
/* animateTraining preserves the state of appData.animate
* when Training mode is activated. This allows the
* response to be animated when appData.animate == TRUE and
* appData.animateDragging == TRUE.
*/
Boolean animateTraining;
GameInfo gameInfo;
AppData appData;
Board boards[MAX_MOVES];
/* [HGM] Following 7 needed for accurate legality tests: */
signed char castlingRank[BOARD_FILES]; // and corresponding ranks
unsigned char initialRights[BOARD_FILES];
int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
int initialRulePlies, FENrulePlies;
FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
int loadFlag = 0;
Boolean shuffleOpenings;
int mute; // mute all sounds
// [HGM] vari: next 12 to save and restore variations
#define MAX_VARIATIONS 10
int framePtr = MAX_MOVES-1; // points to free stack entry
int storedGames = 0;
int savedFirst[MAX_VARIATIONS];
int savedLast[MAX_VARIATIONS];
int savedFramePtr[MAX_VARIATIONS];
char *savedDetails[MAX_VARIATIONS];
ChessMove savedResult[MAX_VARIATIONS];
void PushTail P((int firstMove, int lastMove));
Boolean PopTail P((Boolean annotate));
void PushInner P((int firstMove, int lastMove));
void PopInner P((Boolean annotate));
void CleanupTail P((void));
ChessSquare FIDEArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackKnight, BlackRook }
};
ChessSquare twoKingsArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen,
BlackKing, BlackKing, BlackKnight, BlackRook }
};
ChessSquare KnightmateArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
{ BlackRook, BlackMan, BlackBishop, BlackQueen,
BlackUnicorn, BlackBishop, BlackMan, BlackRook }
};
ChessSquare SpartanArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackAlfil, BlackDragon, BlackKing, BlackTower,
BlackTower, BlackKing, BlackAngel, BlackAlfil }
};
ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
};
ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackKing,
BlackFerz, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackMan, BlackFerz,
BlackKing, BlackMan, BlackKnight, BlackRook }
};
ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
{ WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackMan, BlackFerz,
BlackKing, BlackMan, BlackKnight, BlackRook }
};
ChessSquare lionArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackLion, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackKnight, BlackRook }
};
#if (BOARD_FILES>=10)
ChessSquare ShogiArray[2][BOARD_FILES] = {
{ WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
{ BlackQueen, BlackKnight, BlackFerz, BlackWazir,
BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
};
ChessSquare XiangqiArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackFerz,
BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare CapablancaArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
};
ChessSquare GreatArray[2][BOARD_FILES] = {
{ WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
{ BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
};
ChessSquare JanusArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
{ BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
};
ChessSquare GrandArray[2][BOARD_FILES] = {
{ EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
{ EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
};
ChessSquare ChuChessArray[2][BOARD_FILES] = {
{ WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
{ BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
};
#ifdef GOTHIC
ChessSquare GothicArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
};
#else // !GOTHIC
#define GothicArray CapablancaArray
#endif // !GOTHIC
#ifdef FALCON
ChessSquare FalconArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
};
#else // !FALCON
#define FalconArray CapablancaArray
#endif // !FALCON
#else // !(BOARD_FILES>=10)
#define XiangqiPosition FIDEArray
#define CapablancaArray FIDEArray
#define GothicArray FIDEArray
#define GreatArray FIDEArray
#endif // !(BOARD_FILES>=10)
#if (BOARD_FILES>=12)
ChessSquare CourierArray[2][BOARD_FILES] = {
{ WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
{ BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
};
ChessSquare ChuArray[6][BOARD_FILES] = {
{ WhiteLance, WhiteCat, WhiteCopper, WhiteFerz, WhiteWazir, WhiteKing,
WhiteAlfil, WhiteWazir, WhiteFerz, WhiteCopper, WhiteCat, WhiteLance },
{ BlackLance, BlackCat, BlackCopper, BlackFerz, BlackWazir, BlackAlfil,
BlackKing, BlackWazir, BlackFerz, BlackCopper, BlackCat, BlackLance },
{ WhiteAxe, EmptySquare, WhiteBishop, EmptySquare, WhiteClaw, WhiteMarshall,
WhiteAngel, WhiteClaw, EmptySquare, WhiteBishop, EmptySquare, WhiteAxe },
{ BlackAxe, EmptySquare, BlackBishop, EmptySquare, BlackClaw, BlackAngel,
BlackMarshall, BlackClaw, EmptySquare, BlackBishop, EmptySquare, BlackAxe },
{ WhiteDagger, WhiteSword, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSword, WhiteDagger },
{ BlackDagger, BlackSword, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSword, BlackDagger }
};
#else // !(BOARD_FILES>=12)
#define CourierArray CapablancaArray
#define ChuArray CapablancaArray
#endif // !(BOARD_FILES>=12)
Board initialPosition;
/* Convert str to a rating. Checks for special cases of "----",
"++++", etc. Also strips ()'s */
int
string_to_rating (char *str)
{
while(*str && !isdigit(*str)) ++str;
if (!*str)
return 0; /* One of the special "no rating" cases */
else
return atoi(str);
}
void
ClearProgramStats ()
{
/* Init programStats */
programStats.movelist[0] = 0;
programStats.depth = 0;
programStats.nr_moves = 0;
programStats.moves_left = 0;
programStats.nodes = 0;
programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
programStats.score = 0;
programStats.got_only_move = 0;
programStats.got_fail = 0;
programStats.line_is_book = 0;
}
void
CommonEngineInit ()
{ // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
if (appData.firstPlaysBlack) {
first.twoMachinesColor = "black\n";
second.twoMachinesColor = "white\n";
} else {
first.twoMachinesColor = "white\n";
second.twoMachinesColor = "black\n";
}
first.other = &second;
second.other = &first;
{ float norm = 1;
if(appData.timeOddsMode) {
norm = appData.timeOdds[0];
if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
}
first.timeOdds = appData.timeOdds[0]/norm;
second.timeOdds = appData.timeOdds[1]/norm;
}
if(programVersion) free(programVersion);
if (appData.noChessProgram) {
programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
sprintf(programVersion, "%s", PACKAGE_STRING);
} else {
/* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
}
}
void
UnloadEngine (ChessProgramState *cps)
{
/* Kill off first chess program */
if (cps->isr != NULL)
RemoveInputSource(cps->isr);
cps->isr = NULL;
if (cps->pr != NoProc) {
ExitAnalyzeMode();
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", cps);
DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
}
cps->pr = NoProc;
if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
}
void
ClearOptions (ChessProgramState *cps)
{
int i;
cps->nrOptions = cps->comboCnt = 0;
for(i=0; i<MAX_OPTIONS; i++) {
cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
cps->option[i].textValue = 0;
}
}
char *engineNames[] = {
/* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
N_("first"),
/* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
N_("second")
};
void
InitEngine (ChessProgramState *cps, int n)
{ // [HGM] all engine initialiation put in a function that does one engine
ClearOptions(cps);
cps->which = engineNames[n];
cps->maybeThinking = FALSE;
cps->pr = NoProc;
cps->isr = NULL;
cps->sendTime = 2;
cps->sendDrawOffers = 1;
cps->program = appData.chessProgram[n];
cps->host = appData.host[n];
cps->dir = appData.directory[n];
cps->initString = appData.engInitString[n];
cps->computerString = appData.computerString[n];
cps->useSigint = TRUE;
cps->useSigterm = TRUE;
cps->reuse = appData.reuse[n];
cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
cps->useSetboard = FALSE;
cps->useSAN = FALSE;
cps->usePing = FALSE;
cps->lastPing = 0;
cps->lastPong = 0;
cps->usePlayother = FALSE;
cps->useColors = TRUE;
cps->useUsermove = FALSE;
cps->sendICS = FALSE;
cps->sendName = appData.icsActive;
cps->sdKludge = FALSE;
cps->stKludge = FALSE;
if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
TidyProgramName(cps->program, cps->host, cps->tidy);
cps->matchWins = 0;
ASSIGN(cps->variants, appData.noChessProgram ? "" : appData.variant);
cps->analysisSupport = 2; /* detect */
cps->analyzing = FALSE;
cps->initDone = FALSE;
cps->reload = FALSE;
cps->pseudo = appData.pseudo[n];
/* New features added by Tord: */
cps->useFEN960 = FALSE;
cps->useOOCastle = TRUE;
/* End of new features added by Tord. */
cps->fenOverride = appData.fenOverride[n];
/* [HGM] time odds: set factor for each machine */
cps->timeOdds = appData.timeOdds[n];
/* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
cps->accumulateTC = appData.accumulateTC[n];
cps->maxNrOfSessions = 1;
/* [HGM] debug */
cps->debug = FALSE;
cps->drawDepth = appData.drawDepth[n];
cps->supportsNPS = UNKNOWN;
cps->memSize = FALSE;
cps->maxCores = FALSE;
ASSIGN(cps->egtFormats, "");
/* [HGM] options */
cps->optionSettings = appData.engOptions[n];
cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
cps->isUCI = appData.isUCI[n]; /* [AS] */
cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
cps->highlight = 0;
if (appData.protocolVersion[n] > PROTOVER
|| appData.protocolVersion[n] < 1)
{
char buf[MSG_SIZ];
int len;
len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
appData.protocolVersion[n]);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
DisplayFatalError(buf, 0, 2);
}
else
{
cps->protocolVersion = appData.protocolVersion[n];
}
InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
ParseFeatures(appData.featureDefaults, cps);
}
ChessProgramState *savCps;
GameMode oldMode;
void
LoadEngine ()
{
int i;
if(WaitForEngine(savCps, LoadEngine)) return;
CommonEngineInit(); // recalculate time odds
if(gameInfo.variant != StringToVariant(appData.variant)) {
// we changed variant when loading the engine; this forces us to reset
Reset(TRUE, savCps != &first);
oldMode = BeginningOfGame; // to prevent restoring old mode
}
InitChessProgram(savCps, FALSE);
if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
DisplayMessage("", "");
if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
ThawUI();
SetGNUMode();
if(oldMode == AnalyzeMode) AnalyzeModeEvent();
}
void
ReplaceEngine (ChessProgramState *cps, int n)
{
oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
keepInfo = 1;
if(oldMode != BeginningOfGame) EditGameEvent();
keepInfo = 0;
UnloadEngine(cps);
appData.noChessProgram = FALSE;
appData.clockMode = TRUE;
InitEngine(cps, n);
UpdateLogos(TRUE);
if(n) return; // only startup first engine immediately; second can wait
savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
LoadEngine();
}
extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
static char resetOptions[] =
"-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
"-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
"-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
"-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
void
FloatToFront(char **list, char *engineLine)
{
char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
int i=0;
if(appData.recentEngines <= 0) return;
TidyProgramName(engineLine, "localhost", tidy+1);
tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
strncpy(buf+1, *list, MSG_SIZ-50);
if(p = strstr(buf, tidy)) { // tidy name appears in list
q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
while(*p++ = *++q); // squeeze out
}
strcat(tidy, buf+1); // put list behind tidy name
p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
ASSIGN(*list, tidy+1);
}
char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
void
Load (ChessProgramState *cps, int i)
{
char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
if(engineLine && engineLine[0]) { // an engine was selected from the combo box
snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
appData.firstProtocolVersion = PROTOVER;
ParseArgsFromString(buf);
SwapEngines(i);
ReplaceEngine(cps, i);
FloatToFront(&appData.recentEngineList, engineLine);
if(gameMode == BeginningOfGame) Reset(TRUE, TRUE);
return;
}
p = engineName;
while(q = strchr(p, SLASH)) p = q+1;
if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
if(engineDir[0] != NULLCHAR) {
ASSIGN(appData.directory[i], engineDir); p = engineName;
} else if(p != engineName) { // derive directory from engine path, when not given
p[-1] = 0;
ASSIGN(appData.directory[i], engineName);
p[-1] = SLASH;
if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
} else { ASSIGN(appData.directory[i], "."); }
jar = (strstr(p, ".jar") == p + strlen(p) - 4);
if(params[0]) {
if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
snprintf(command, MSG_SIZ, "%s %s", p, params);
p = command;
}
if(jar) { snprintf(buf3, MSG_SIZ, "java -jar %s", p); p = buf3; }
ASSIGN(appData.chessProgram[i], p);
appData.isUCI[i] = isUCI;
appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
appData.hasOwnBookUCI[i] = hasBook;
if(!nickName[0]) useNick = FALSE;
if(useNick) ASSIGN(appData.pgnName[i], nickName);
if(addToList) {
int len;
char quote;
q = firstChessProgramNames;
if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
quote, p, quote, appData.directory[i],
useNick ? " -fn \"" : "",
useNick ? nickName : "",
useNick ? "\"" : "",
v1 ? " -firstProtocolVersion 1" : "",
hasBook ? "" : " -fNoOwnBookUCI",
isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
storeVariant ? " -variant " : "",
storeVariant ? VariantName(gameInfo.variant) : "");
if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
if(insert != q) insert[-1] = NULLCHAR;
snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
if(q) free(q);
FloatToFront(&appData.recentEngineList, buf);
}
ReplaceEngine(cps, i);
}
void
InitTimeControls ()
{
int matched, min, sec;
/*
* Parse timeControl resource
*/
if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
appData.movesPerSession)) {
char buf[MSG_SIZ];
snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
DisplayFatalError(buf, 0, 2);
}
/*
* Parse searchTime resource
*/
if (*appData.searchTime != NULLCHAR) {
matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
if (matched == 1) {
searchTime = min * 60;
} else if (matched == 2) {
searchTime = min * 60 + sec;
} else {
char buf[MSG_SIZ];
snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
DisplayFatalError(buf, 0, 2);
}
}
}
void
InitBackEnd1 ()
{
ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
GetTimeMark(&programStartTime);
srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
appData.seedBase = random() + (random()<<15);
pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
ClearProgramStats();
programStats.ok_to_send = 1;
programStats.seen_stat = 0;
/*
* Initialize game list
*/
ListNew(&gameList);
/*
* Internet chess server status
*/
if (appData.icsActive) {
appData.matchMode = FALSE;
appData.matchGames = 0;
#if ZIPPY
appData.noChessProgram = !appData.zippyPlay;
#else
appData.zippyPlay = FALSE;
appData.zippyTalk = FALSE;
appData.noChessProgram = TRUE;
#endif
if (*appData.icsHelper != NULLCHAR) {
appData.useTelnet = TRUE;
appData.telnetProgram = appData.icsHelper;
}
} else {
appData.zippyTalk = appData.zippyPlay = FALSE;
}
/* [AS] Initialize pv info list [HGM] and game state */
{
int i, j;
for( i=0; i<=framePtr; i++ ) {
pvInfoList[i].depth = -1;
boards[i][EP_STATUS] = EP_NONE;
for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
}
}
InitTimeControls();
/* [AS] Adjudication threshold */
adjudicateLossThreshold = appData.adjudicateLossThreshold;
InitEngine(&first, 0);
InitEngine(&second, 1);
CommonEngineInit();
pairing.which = "pairing"; // pairing engine
pairing.pr = NoProc;
pairing.isr = NULL;
pairing.program = appData.pairingEngine;
pairing.host = "localhost";
pairing.dir = ".";
if (appData.icsActive) {
appData.clockMode = TRUE; /* changes dynamically in ICS mode */
} else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
appData.clockMode = FALSE;
first.sendTime = second.sendTime = 0;
}
#if ZIPPY
/* Override some settings from environment variables, for backward
compatibility. Unfortunately it's not feasible to have the env
vars just set defaults, at least in xboard. Ugh.
*/
if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
ZippyInit();
}
#endif
if (!appData.icsActive) {
char buf[MSG_SIZ];
int len;
/* Check for variants that are supported only in ICS mode,
or not at all. Some that are accepted here nevertheless
have bugs; see comments below.
*/
VariantClass variant = StringToVariant(appData.variant);
switch (variant) {
case VariantBughouse: /* need four players and two boards */
case VariantKriegspiel: /* need to hide pieces and move details */
/* case VariantFischeRandom: (Fabien: moved below) */
len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
DisplayFatalError(buf, 0, 2);
return;
case VariantUnknown:
case VariantLoadable:
case Variant29:
case Variant30:
case Variant31:
case Variant32:
case Variant33:
case Variant34:
case Variant35:
case Variant36:
default:
len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
DisplayFatalError(buf, 0, 2);
return;
case VariantNormal: /* definitely works! */
if(strcmp(appData.variant, "normal") && !appData.noChessProgram) { // [HGM] hope this is an engine-defined variant
safeStrCpy(engineVariant, appData.variant, MSG_SIZ);
return;
}
case VariantXiangqi: /* [HGM] repetition rules not implemented */
case VariantFairy: /* [HGM] TestLegality definitely off! */
case VariantGothic: /* [HGM] should work */
case VariantCapablanca: /* [HGM] should work */
case VariantCourier: /* [HGM] initial forced moves not implemented */
case VariantShogi: /* [HGM] could still mate with pawn drop */
case VariantChu: /* [HGM] experimental */
case VariantKnightmate: /* [HGM] should work */
case VariantCylinder: /* [HGM] untested */
case VariantFalcon: /* [HGM] untested */
case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
offboard interposition not understood */
case VariantWildCastle: /* pieces not automatically shuffled */
case VariantNoCastle: /* pieces not automatically shuffled */
case VariantFischeRandom: /* [HGM] works and shuffles pieces */
case VariantLosers: /* should work except for win condition,
and doesn't know captures are mandatory */
case VariantSuicide: /* should work except for win condition,
and doesn't know captures are mandatory */
case VariantGiveaway: /* should work except for win condition,
and doesn't know captures are mandatory */
case VariantTwoKings: /* should work */
case VariantAtomic: /* should work except for win condition */
case Variant3Check: /* should work except for win condition */
case VariantShatranj: /* should work except for all win conditions */
case VariantMakruk: /* should work except for draw countdown */
case VariantASEAN : /* should work except for draw countdown */
case VariantBerolina: /* might work if TestLegality is off */
case VariantCapaRandom: /* should work */
case VariantJanus: /* should work */
case VariantSuper: /* experimental */
case VariantGreat: /* experimental, requires legality testing to be off */
case VariantSChess: /* S-Chess, should work */
case VariantGrand: /* should work */
case VariantSpartan: /* should work */
case VariantLion: /* should work */
case VariantChuChess: /* should work */
break;
}
}
}
int
NextIntegerFromString (char ** str, long * value)
{
int result = -1;
char * s = *str;
while( *s == ' ' || *s == '\t' ) {
s++;
}
*value = 0;
if( *s >= '0' && *s <= '9' ) {
while( *s >= '0' && *s <= '9' ) {
*value = *value * 10 + (*s - '0');
s++;
}
result = 0;
}
*str = s;
return result;
}
int
NextTimeControlFromString (char ** str, long * value)
{
long temp;
int result = NextIntegerFromString( str, &temp );
if( result == 0 ) {
*value = temp * 60; /* Minutes */
if( **str == ':' ) {
(*str)++;
result = NextIntegerFromString( str, &temp );
*value += temp; /* Seconds */
}
}
return result;
}
int
NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
{ /* [HGM] routine added to read '+moves/time' for secondary time control. */
int result = -1, type = 0; long temp, temp2;
if(**str != ':') return -1; // old params remain in force!
(*str)++;
if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
if( NextIntegerFromString( str, &temp ) ) return -1;
if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
if(**str != '/') {
/* time only: incremental or sudden-death time control */
if(**str == '+') { /* increment follows; read it */
(*str)++;
if(**str == '!') type = *(*str)++; // Bronstein TC
if(result = NextIntegerFromString( str, &temp2)) return -1;
*inc = temp2 * 1000;
if(**str == '.') { // read fraction of increment
char *start = ++(*str);
if(result = NextIntegerFromString( str, &temp2)) return -1;
temp2 *= 1000;
while(start++ < *str) temp2 /= 10;
*inc += temp2;
}
} else *inc = 0;
*moves = 0; *tc = temp * 1000; *incType = type;
return 0;
}
(*str)++; /* classical time control */
result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
if(result == 0) {
*moves = temp;
*tc = temp2 * 1000;
*inc = 0;
*incType = type;
}
return result;
}
int
GetTimeQuota (int movenr, int lastUsed, char *tcString)
{ /* [HGM] get time to add from the multi-session time-control string */
int incType, moves=1; /* kludge to force reading of first session */
long time, increment;
char *s = tcString;
if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
do {
if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
nextSession = s; suddenDeath = moves == 0 && increment == 0;
if(movenr == -1) return time; /* last move before new session */
if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
if(incType == '!' && lastUsed < increment) increment = lastUsed;
if(!moves) return increment; /* current session is incremental */
if(movenr >= 0) movenr -= moves; /* we already finished this session */
} while(movenr >= -1); /* try again for next session */
return 0; // no new time quota on this move
}
int
ParseTimeControl (char *tc, float ti, int mps)
{
long tc1;
long tc2;
char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
int min, sec=0;
if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
if(ti > 0) {
if(mps)
snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
else
snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
} else {
if(mps)
snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
else
snprintf(buf, MSG_SIZ, ":%s", mytc);
}
fullTimeControlString = StrSave(buf); // this should now be in PGN format
if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
return FALSE;
}
if( *tc == '/' ) {
/* Parse second time control */
tc++;
if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
return FALSE;
}
if( tc2 == 0 ) {
return FALSE;
}
timeControl_2 = tc2 * 1000;
}
else {
timeControl_2 = 0;
}
if( tc1 == 0 ) {
return FALSE;
}
timeControl = tc1 * 1000;
if (ti >= 0) {
timeIncrement = ti * 1000; /* convert to ms */
movesPerSession = 0;
} else {
timeIncrement = 0;
movesPerSession = mps;
}
return TRUE;
}
void
InitBackEnd2 ()
{
if (appData.debugMode) {
# ifdef __GIT_VERSION
fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
# else
fprintf(debugFP, "Version: %s\n", programVersion);
# endif
}
ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
set_cont_sequence(appData.wrapContSeq);
if (appData.matchGames > 0) {
appData.matchMode = TRUE;
} else if (appData.matchMode) {
appData.matchGames = 1;
}
if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
appData.matchGames = appData.sameColorGames;
if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
}
Reset(TRUE, FALSE);
if (appData.noChessProgram || first.protocolVersion == 1) {
InitBackEnd3();
} else {
/* kludge: allow timeout for initial "feature" commands */
FreezeUI();
DisplayMessage("", _("Starting chess program"));
ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
}
}
int
CalculateIndex (int index, int gameNr)
{ // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
int res;
if(index > 0) return index; // fixed nmber
if(index == 0) return 1;
res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
return res;
}
int
LoadGameOrPosition (int gameNr)
{ // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
if (*appData.loadGameFile != NULLCHAR) {
if (!LoadGameFromFile(appData.loadGameFile,
CalculateIndex(appData.loadGameIndex, gameNr),
appData.loadGameFile, FALSE)) {
DisplayFatalError(_("Bad game file"), 0, 1);
return 0;
}
} else if (*appData.loadPositionFile != NULLCHAR) {
if (!LoadPositionFromFile(appData.loadPositionFile,
CalculateIndex(appData.loadPositionIndex, gameNr),
appData.loadPositionFile)) {
DisplayFatalError(_("Bad position file"), 0, 1);
return 0;
}
}
return 1;
}
void
ReserveGame (int gameNr, char resChar)
{
FILE *tf = fopen(appData.tourneyFile, "r+");
char *p, *q, c, buf[MSG_SIZ];
if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
safeStrCpy(buf, lastMsg, MSG_SIZ);
DisplayMessage(_("Pick new game"), "");
flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
ParseArgsFromFile(tf);
p = q = appData.results;
if(appData.debugMode) {
char *r = appData.participants;
fprintf(debugFP, "results = '%s'\n", p);
while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
fprintf(debugFP, "\n");
}
while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
nextGame = q - p;
q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
safeStrCpy(q, p, strlen(p) + 2);
if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
q[nextGame] = '*';
}
fseek(tf, -(strlen(p)+4), SEEK_END);
c = fgetc(tf);
if(c != '"') // depending on DOS or Unix line endings we can be one off
fseek(tf, -(strlen(p)+2), SEEK_END);
else fseek(tf, -(strlen(p)+3), SEEK_END);
fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
DisplayMessage(buf, "");
free(p); appData.results = q;
if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
(gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
int round = appData.defaultMatchGames * appData.tourneyType;
if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
UnloadEngine(&first); // next game belongs to other pairing;
UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
}
if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
}
void
MatchEvent (int mode)
{ // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
int dummy;
if(matchMode) { // already in match mode: switch it off
abortMatch = TRUE;
if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
return;
}
// if(gameMode != BeginningOfGame) {
// DisplayError(_("You can only start a match from the initial position."), 0);
// return;
// }
abortMatch = FALSE;
if(mode == 2) appData.matchGames = appData.defaultMatchGames;
/* Set up machine vs. machine match */
nextGame = 0;
NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
if(appData.tourneyFile[0]) {
ReserveGame(-1, 0);
if(nextGame > appData.matchGames) {
char buf[MSG_SIZ];
if(strchr(appData.results, '*') == NULL) {
FILE *f;
appData.tourneyCycles++;
if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
fclose(f);
NextTourneyGame(-1, &dummy);
ReserveGame(-1, 0);
if(nextGame <= appData.matchGames) {
DisplayNote(_("You restarted an already completed tourney.\nOne more cycle will now be added to it.\nGames commence in 10 sec."));
matchMode = mode;
ScheduleDelayedEvent(NextMatchGame, 10000);
return;
}
}
}
snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
DisplayError(buf, 0);
appData.tourneyFile[0] = 0;
return;
}
} else
if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
DisplayFatalError(_("Can't have a match with no chess programs"),
0, 2);
return;
}
matchMode = mode;
matchGame = roundNr = 1;
first.matchWins = second.matchWins = totalTime = 0; // [HGM] match: needed in later matches
NextMatchGame();
}
char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
void
InitBackEnd3 P((void))
{
GameMode initialMode;
char buf[MSG_SIZ];
int err, len;
if(!appData.icsActive && !appData.noChessProgram && !appData.matchMode && // mode involves only first engine
!strcmp(appData.variant, "normal") && // no explicit variant request
appData.NrRanks == -1 && appData.NrFiles == -1 && appData.holdingsSize == -1 && // no size overrides requested
!SupportedVariant(first.variants, VariantNormal, 8, 8, 0, first.protocolVersion, "") && // but 'normal' won't work with engine
!SupportedVariant(first.variants, VariantFischeRandom, 8, 8, 0, first.protocolVersion, "") ) { // nor will Chess960
char c, *q = first.variants, *p = strchr(q, ',');
if(p) *p = NULLCHAR;
if(StringToVariant(q) != VariantUnknown) { // the engine can play a recognized variant, however
int w, h, s;
if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
ASSIGN(appData.variant, q); // fake user requested the first variant played by the engine
Reset(TRUE, FALSE); // and re-initialize
}
if(p) *p = ',';
}
InitChessProgram(&first, startedFromSetupPosition);
if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
free(programVersion);
programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
}
if (appData.icsActive) {
#ifdef WIN32
/* [DM] Make a console window if needed [HGM] merged ifs */
ConsoleCreate();
#endif
err = establish();
if (err != 0)
{
if (*appData.icsCommPort != NULLCHAR)
len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
appData.icsCommPort);
else
len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
appData.icsHost, appData.icsPort);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
DisplayFatalError(buf, err, 1);
return;
}
SetICSMode();
telnetISR =
AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
fromUserISR =
AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
} else if (appData.noChessProgram) {
SetNCPMode();
} else {
SetGNUMode();
}
if (*appData.cmailGameName != NULLCHAR) {
SetCmailMode();
OpenLoopback(&cmailPR);
cmailISR =
AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
}
ThawUI();
DisplayMessage("", "");
if (StrCaseCmp(appData.initialMode, "") == 0) {
initialMode = BeginningOfGame;
if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
ModeHighlight();
}
} else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
initialMode = TwoMachinesPlay;
} else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
initialMode = AnalyzeFile;
} else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
initialMode = AnalyzeMode;
} else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
initialMode = MachinePlaysWhite;
} else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
initialMode = MachinePlaysBlack;
} else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
initialMode = EditGame;
} else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
initialMode = EditPosition;
} else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
initialMode = Training;
} else {
len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
DisplayFatalError(buf, 0, 2);
return;
}
if (appData.matchMode) {
if(appData.tourneyFile[0]) { // start tourney from command line
FILE *f;
if(f = fopen(appData.tourneyFile, "r")) {
ParseArgsFromFile(f); // make sure tourney parmeters re known
fclose(f);
appData.clockMode = TRUE;
SetGNUMode();
} else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
}
MatchEvent(TRUE);
} else if (*appData.cmailGameName != NULLCHAR) {
/* Set up cmail mode */
ReloadCmailMsgEvent(TRUE);
} else {
/* Set up other modes */
if (initialMode == AnalyzeFile) {
if (*appData.loadGameFile == NULLCHAR) {
DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
return;
}
}
if (*appData.loadGameFile != NULLCHAR) {
(void) LoadGameFromFile(appData.loadGameFile,
appData.loadGameIndex,
appData.loadGameFile, TRUE);
} else if (*appData.loadPositionFile != NULLCHAR) {
(void) LoadPositionFromFile(appData.loadPositionFile,
appData.loadPositionIndex,
appData.loadPositionFile);
/* [HGM] try to make self-starting even after FEN load */
/* to allow automatic setup of fairy variants with wtm */
if(initialMode == BeginningOfGame && !blackPlaysFirst) {
gameMode = BeginningOfGame;
setboardSpoiledMachineBlack = 1;
}
/* [HGM] loadPos: make that every new game uses the setup */
/* from file as long as we do not switch variant */
if(!blackPlaysFirst) {
startedFromPositionFile = TRUE;
CopyBoard(filePosition, boards[0]);
CopyBoard(initialPosition, boards[0]);
}
} else if(*appData.fen != NULLCHAR) {
if(ParseFEN(filePosition, &blackPlaysFirst, appData.fen, TRUE) && !blackPlaysFirst) {
startedFromPositionFile = TRUE;
Reset(TRUE, TRUE);
}
}
if (initialMode == AnalyzeMode) {
if (appData.noChessProgram) {
DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
return;
}
if (appData.icsActive) {
DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
return;
}
AnalyzeModeEvent();
} else if (initialMode == AnalyzeFile) {
appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
ShowThinkingEvent();
AnalyzeFileEvent();
AnalysisPeriodicEvent(1);
} else if (initialMode == MachinePlaysWhite) {
if (appData.noChessProgram) {
DisplayFatalError(_("MachineWhite mode requires a chess engine"),
0, 2);
return;
}
if (appData.icsActive) {
DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
0, 2);
return;
}
MachineWhiteEvent();
} else if (initialMode == MachinePlaysBlack) {
if (appData.noChessProgram) {
DisplayFatalError(_("MachineBlack mode requires a chess engine"),
0, 2);
return;
}
if (appData.icsActive) {
DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
0, 2);
return;
}
MachineBlackEvent();
} else if (initialMode == TwoMachinesPlay) {
if (appData.noChessProgram) {
DisplayFatalError(_("TwoMachines mode requires a chess engine"),
0, 2);
return;
}
if (appData.icsActive) {
DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
0, 2);
return;
}
TwoMachinesEvent();
} else if (initialMode == EditGame) {
EditGameEvent();
} else if (initialMode == EditPosition) {
EditPositionEvent();
} else if (initialMode == Training) {
if (*appData.loadGameFile == NULLCHAR) {
DisplayFatalError(_("Training mode requires a game file"), 0, 2);
return;
}
TrainingEvent();
}
}
}
void
HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
{
DisplayBook(current+1);
MoveHistorySet( movelist, first, last, current, pvInfoList );
EvalGraphSet( first, last, current, pvInfoList );
MakeEngineOutputTitle();
}
/*
* Establish will establish a contact to a remote host.port.
* Sets icsPR to a ProcRef for a process (or pseudo-process)
* used to talk to the host.
* Returns 0 if okay, error code if not.
*/
int
establish ()
{
char buf[MSG_SIZ];
if (*appData.icsCommPort != NULLCHAR) {
/* Talk to the host through a serial comm port */
return OpenCommPort(appData.icsCommPort, &icsPR);
} else if (*appData.gateway != NULLCHAR) {
if (*appData.remoteShell == NULLCHAR) {
/* Use the rcmd protocol to run telnet program on a gateway host */
snprintf(buf, sizeof(buf), "%s %s %s",
appData.telnetProgram, appData.icsHost, appData.icsPort);
return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
} else {
/* Use the rsh program to run telnet program on a gateway host */
if (*appData.remoteUser == NULLCHAR) {
snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
appData.gateway, appData.telnetProgram,
appData.icsHost, appData.icsPort);
} else {
snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
appData.remoteShell, appData.gateway,
appData.remoteUser, appData.telnetProgram,
appData.icsHost, appData.icsPort);
}
return StartChildProcess(buf, "", &icsPR);
}
} else if (appData.useTelnet) {
return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
} else {
/* TCP socket interface differs somewhat between
Unix and NT; handle details in the front end.
*/
return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
}
}
void
EscapeExpand (char *p, char *q)
{ // [HGM] initstring: routine to shape up string arguments
while(*p++ = *q++) if(p[-1] == '\\')
switch(*q++) {
case 'n': p[-1] = '\n'; break;
case 'r': p[-1] = '\r'; break;
case 't': p[-1] = '\t'; break;
case '\\': p[-1] = '\\'; break;
case 0: *p = 0; return;
default: p[-1] = q[-1]; break;
}
}
void
show_bytes (FILE *fp, char *buf, int count)
{
while (count--) {
if (*buf < 040 || *(unsigned char *) buf > 0177) {
fprintf(fp, "\\%03o", *buf & 0xff);
} else {
putc(*buf, fp);
}
buf++;
}
fflush(fp);
}
/* Returns an errno value */
int
OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
{
char buf[8192], *p, *q, *buflim;
int left, newcount, outcount;
if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
*appData.gateway != NULLCHAR) {
if (appData.debugMode) {
fprintf(debugFP, ">ICS: ");
show_bytes(debugFP, message, count);
fprintf(debugFP, "\n");
}
return OutputToProcess(pr, message, count, outError);
}
buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
p = message;
q = buf;
left = count;
newcount = 0;
while (left) {
if (q >= buflim) {
if (appData.debugMode) {
fprintf(debugFP, ">ICS: ");
show_bytes(debugFP, buf, newcount);
fprintf(debugFP, "\n");
}
outcount = OutputToProcess(pr, buf, newcount, outError);
if (outcount < newcount) return -1; /* to be sure */
q = buf;
newcount = 0;
}
if (*p == '\n') {
*q++ = '\r';
newcount++;
} else if (((unsigned char) *p) == TN_IAC) {
*q++ = (char) TN_IAC;
newcount ++;
}
*q++ = *p++;
newcount++;
left--;
}
if (appData.debugMode) {
fprintf(debugFP, ">ICS: ");
show_bytes(debugFP, buf, newcount);
fprintf(debugFP, "\n");
}
outcount = OutputToProcess(pr, buf, newcount, outError);
if (outcount < newcount) return -1; /* to be sure */
return count;
}
void
read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
{
int outError, outCount;
static int gotEof = 0;
static FILE *ini;
/* Pass data read from player on to ICS */
if (count > 0) {
gotEof = 0;
outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
if (outCount < count) {
DisplayFatalError(_("Error writing to ICS"), outError, 1);
}
if(have_sent_ICS_logon == 2) {
if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
fprintf(ini, "%s", message);
have_sent_ICS_logon = 3;
} else
have_sent_ICS_logon = 1;
} else if(have_sent_ICS_logon == 3) {
fprintf(ini, "%s", message);
fclose(ini);
have_sent_ICS_logon = 1;
}
} else if (count < 0) {
RemoveInputSource(isr);
DisplayFatalError(_("Error reading from keyboard"), error, 1);
} else if (gotEof++ > 0) {
RemoveInputSource(isr);
DisplayFatalError(_("Got end of file from keyboard"), 0, 666); // [HGM] 666 is kludge to alert front end
}
}
void
KeepAlive ()
{ // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
connectionAlive = FALSE; // only sticks if no response to 'date' command.
SendToICS("date\n");
if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
}
/* added routine for printf style output to ics */
void
ics_printf (char *format, ...)
{
char buffer[MSG_SIZ];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
buffer[sizeof(buffer)-1] = '\0';
SendToICS(buffer);
va_end(args);
}
void
SendToICS (char *s)
{
int count, outCount, outError;
if (icsPR == NoProc) return;
count = strlen(s);
outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
if (outCount < count) {
DisplayFatalError(_("Error writing to ICS"), outError, 1);
}
}
/* This is used for sending logon scripts to the ICS. Sending
without a delay causes problems when using timestamp on ICC
(at least on my machine). */
void
SendToICSDelayed (char *s, long msdelay)
{
int count, outCount, outError;
if (icsPR == NoProc) return;
count = strlen(s);
if (appData.debugMode) {
fprintf(debugFP, ">ICS: ");
show_bytes(debugFP, s, count);
fprintf(debugFP, "\n");
}
outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
msdelay);
if (outCount < count) {
DisplayFatalError(_("Error writing to ICS"), outError, 1);
}
}
/* Remove all highlighting escape sequences in s
Also deletes any suffix starting with '('
*/
char *
StripHighlightAndTitle (char *s)
{
static char retbuf[MSG_SIZ];
char *p = retbuf;
while (*s != NULLCHAR) {
while (*s == '\033') {
while (*s != NULLCHAR && !isalpha(*s)) s++;
if (*s != NULLCHAR) s++;
}
while (*s != NULLCHAR && *s != '\033') {
if (*s == '(' || *s == '[') {
*p = NULLCHAR;
return retbuf;
}
*p++ = *s++;
}
}
*p = NULLCHAR;
return retbuf;
}
/* Remove all highlighting escape sequences in s */
char *
StripHighlight (char *s)
{
static char retbuf[MSG_SIZ];
char *p = retbuf;
while (*s != NULLCHAR) {
while (*s == '\033') {
while (*s != NULLCHAR && !isalpha(*s)) s++;
if (*s != NULLCHAR) s++;
}
while (*s != NULLCHAR && *s != '\033') {
*p++ = *s++;
}
}
*p = NULLCHAR;
return retbuf;
}
char engineVariant[MSG_SIZ];
char *variantNames[] = VARIANT_NAMES;
char *
VariantName (VariantClass v)
{
if(v == VariantUnknown || *engineVariant) return engineVariant;
return variantNames[v];
}
/* Identify a variant from the strings the chess servers use or the
PGN Variant tag names we use. */
VariantClass
StringToVariant (char *e)
{
char *p;
int wnum = -1;
VariantClass v = VariantNormal;
int i, found = FALSE;
char buf[MSG_SIZ], c;
int len;
if (!e) return v;
/* [HGM] skip over optional board-size prefixes */
if( sscanf(e, "%dx%d_%c", &i, &i, &c) == 3 ||
sscanf(e, "%dx%d+%d_%c", &i, &i, &i, &c) == 4 ) {
while( *e++ != '_');
}
if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
v = VariantNormal;
found = TRUE;
} else
for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
if (p = StrCaseStr(e, variantNames[i])) {
if(p && i >= VariantShogi && (p != e && !appData.icsActive || isalpha(p[strlen(variantNames[i])]))) continue;
v = (VariantClass) i;
found = TRUE;
break;
}
}
if (!found) {
if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
|| StrCaseStr(e, "wild/fr")
|| StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
v = VariantFischeRandom;
} else if ((i = 4, p = StrCaseStr(e, "wild")) ||
(i = 1, p = StrCaseStr(e, "w"))) {
p += i;
while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
if (isdigit(*p)) {
wnum = atoi(p);
} else {
wnum = -1;
}
switch (wnum) {
case 0: /* FICS only, actually */
case 1:
/* Castling legal even if K starts on d-file */
v = VariantWildCastle;
break;
case 2:
case 3:
case 4:
/* Castling illegal even if K & R happen to start in
normal positions. */
v = VariantNoCastle;
break;
case 5:
case 7:
case 8:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 18:
case 19:
/* Castling legal iff K & R start in normal positions */
v = VariantNormal;
break;
case 6:
case 20:
case 21:
/* Special wilds for position setup; unclear what to do here */
v = VariantLoadable;
break;
case 9:
/* Bizarre ICC game */
v = VariantTwoKings;
break;
case 16:
v = VariantKriegspiel;
break;
case 17:
v = VariantLosers;
break;
case 22:
v = VariantFischeRandom;
break;
case 23:
v = VariantCrazyhouse;
break;
case 24:
v = VariantBughouse;
break;
case 25:
v = Variant3Check;
break;
case 26:
/* Not quite the same as FICS suicide! */
v = VariantGiveaway;
break;
case 27:
v = VariantAtomic;
break;
case 28:
v = VariantShatranj;
break;
/* Temporary names for future ICC types. The name *will* change in
the next xboard/WinBoard release after ICC defines it. */
case 29:
v = Variant29;
break;
case 30:
v = Variant30;
break;
case 31:
v = Variant31;
break;
case 32:
v = Variant32;
break;
case 33:
v = Variant33;
break;
case 34:
v = Variant34;
break;
case 35:
v = Variant35;
break;
case 36:
v = Variant36;
break;
case 37:
v = VariantShogi;
break;
case 38:
v = VariantXiangqi;
break;
case 39:
v = VariantCourier;
break;
case 40:
v = VariantGothic;
break;
case 41:
v = VariantCapablanca;
break;
case 42:
v = VariantKnightmate;
break;
case 43:
v = VariantFairy;
break;
case 44:
v = VariantCylinder;
break;
case 45:
v = VariantFalcon;
break;
case 46:
v = VariantCapaRandom;
break;
case 47:
v = VariantBerolina;
break;
case 48:
v = VariantJanus;
break;
case 49:
v = VariantSuper;
break;
case 50:
v = VariantGreat;
break;
case -1:
/* Found "wild" or "w" in the string but no number;
must assume it's normal chess. */
v = VariantNormal;
break;
default:
len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
if( (len >= MSG_SIZ) && appData.debugMode )
fprintf(debugFP, "StringToVariant: buffer truncated.\n");
DisplayError(buf, 0);
v = VariantUnknown;
break;
}
}
}
if (appData.debugMode) {
fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
e, wnum, VariantName(v));
}
return v;
}
static int leftover_start = 0, leftover_len = 0;
char star_match[STAR_MATCH_N][MSG_SIZ];
/* Test whether pattern is present at &buf[*index]; if so, return TRUE,
advance *index beyond it, and set leftover_start to the new value of
*index; else return FALSE. If pattern contains the character '*', it
matches any sequence of characters not containing '\r', '\n', or the
character following the '*' (if any), and the matched sequence(s) are
copied into star_match.
*/
int
looking_at ( char *buf, int *index, char *pattern)
{
char *bufp = &buf[*index], *patternp = pattern;
int star_count = 0;
char *matchp = star_match[0];
for (;;) {
if (*patternp == NULLCHAR) {
*index = leftover_start = bufp - buf;
*matchp = NULLCHAR;
return TRUE;
}
if (*bufp == NULLCHAR) return FALSE;
if (*patternp == '*') {
if (*bufp == *(patternp + 1)) {
*matchp = NULLCHAR;
matchp = star_match[++star_count];
patternp += 2;
bufp++;
continue;
} else if (*bufp == '\n' || *bufp == '\r') {
patternp++;
if (*patternp == NULLCHAR)
continue;
else
return FALSE;
} else {
*matchp++ = *bufp++;
continue;
}
}
if (*patternp != *bufp) return FALSE;
patternp++;
bufp++;
}
}
void
SendToPlayer (char *data, int length)
{
int error, outCount;
outCount = OutputToProcess(NoProc, data, length, &error);
if (outCount < length) {
DisplayFatalError(_("Error writing to display"), error, 1);
}
}
void
PackHolding (char packed[], char *holding)
{
char *p = holding;
char *q = packed;
int runlength = 0;
int curr = 9999;
do {
if (*p == curr) {
runlength++;
} else {
switch (runlength) {
case 0:
break;
case 1:
*q++ = curr;
break;
case 2:
*q++ = curr;
*q++ = curr;
break;
default:
sprintf(q, "%d", runlength);
while (*q) q++;
*q++ = curr;
break;
}
runlength = 1;
curr = *p;
}
} while (*p++);
*q = NULLCHAR;
}
/* Telnet protocol requests from the front end */
void
TelnetRequest (unsigned char ddww, unsigned char option)
{
unsigned char msg[3];
int outCount, outError;
if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
if (appData.debugMode) {
char buf1[8], buf2[8], *ddwwStr, *optionStr;
switch (ddww) {
case TN_DO:
ddwwStr = "DO";
break;
case TN_DONT:
ddwwStr = "DONT";
break;
case TN_WILL:
ddwwStr = "WILL";
break;
case TN_WONT:
ddwwStr = "WONT";
break;
default:
ddwwStr = buf1;
snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
break;
}
switch (option) {
case TN_ECHO:
optionStr = "ECHO";
break;
default:
optionStr = buf2;
snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
break;
}
fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
}
msg[0] = TN_IAC;
msg[1] = ddww;
msg[2] = option;
outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
if (outCount < 3) {
DisplayFatalError(_("Error writing to ICS"), outError, 1);
}
}
void
DoEcho ()
{
if (!appData.icsActive) return;
TelnetRequest(TN_DO, TN_ECHO);
}
void
DontEcho ()
{
if (!appData.icsActive) return;
TelnetRequest(TN_DONT, TN_ECHO);
}
void
CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
{
/* put the holdings sent to us by the server on the board holdings area */
int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
char p;
ChessSquare piece;
if(gameInfo.holdingsWidth < 2) return;
if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
return; // prevent overwriting by pre-board holdings
if( (int)lowestPiece >= BlackPawn ) {
holdingsColumn = 0;
countsColumn = 1;
holdingsStartRow = BOARD_HEIGHT-1;
direction = -1;
} else {
holdingsColumn = BOARD_WIDTH-1;
countsColumn = BOARD_WIDTH-2;
holdingsStartRow = 0;
direction = 1;
}
for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
board[i][holdingsColumn] = EmptySquare;
board[i][countsColumn] = (ChessSquare) 0;
}
while( (p=*holdings++) != NULLCHAR ) {
piece = CharToPiece( ToUpper(p) );
if(piece == EmptySquare) continue;
/*j = (int) piece - (int) WhitePawn;*/
j = PieceToNumber(piece);
if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
if(j < 0) continue; /* should not happen */
piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
board[holdingsStartRow+j*direction][holdingsColumn] = piece;
board[holdingsStartRow+j*direction][countsColumn]++;
}
}
void
VariantSwitch (Board board, VariantClass newVariant)
{
int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
static Board oldBoard;
startedFromPositionFile = FALSE;
if(gameInfo.variant == newVariant) return;
/* [HGM] This routine is called each time an assignment is made to
* gameInfo.variant during a game, to make sure the board sizes
* are set to match the new variant. If that means adding or deleting
* holdings, we shift the playing board accordingly
* This kludge is needed because in ICS observe mode, we get boards
* of an ongoing game without knowing the variant, and learn about the
* latter only later. This can be because of the move list we requested,
* in which case the game history is refilled from the beginning anyway,
* but also when receiving holdings of a crazyhouse game. In the latter
* case we want to add those holdings to the already received position.
*/
if (appData.debugMode) {
fprintf(debugFP, "Switch board from %s to %s\n",
VariantName(gameInfo.variant), VariantName(newVariant));
setbuf(debugFP, NULL);
}
shuffleOpenings = 0; /* [HGM] shuffle */
gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
switch(newVariant)
{
case VariantShogi:
newWidth = 9; newHeight = 9;
gameInfo.holdingsSize = 7;
case VariantBughouse:
case VariantCrazyhouse:
newHoldingsWidth = 2; break;
case VariantGreat:
newWidth = 10;
case VariantSuper:
newHoldingsWidth = 2;
gameInfo.holdingsSize = 8;
break;
case VariantGothic:
case VariantCapablanca:
case VariantCapaRandom:
newWidth = 10;
default:
newHoldingsWidth = gameInfo.holdingsSize = 0;
};
if(newWidth != gameInfo.boardWidth ||
newHeight != gameInfo.boardHeight ||
newHoldingsWidth != gameInfo.holdingsWidth ) {
/* shift position to new playing area, if needed */
if(newHoldingsWidth > gameInfo.holdingsWidth) {
for(i=0; i<BOARD_HEIGHT; i++)
for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
board[i][j];
for(i=0; i<newHeight; i++) {
board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
}
} else if(newHoldingsWidth < gameInfo.holdingsWidth) {
for(i=0; i<BOARD_HEIGHT; i++)
for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
board[i][j];
}
board[HOLDINGS_SET] = 0;
gameInfo.boardWidth = newWidth;
gameInfo.boardHeight = newHeight;
gameInfo.holdingsWidth = newHoldingsWidth;
gameInfo.variant = newVariant;
InitDrawingSizes(-2, 0);
} else gameInfo.variant = newVariant;
CopyBoard(oldBoard, board); // remember correctly formatted board
InitPosition(FALSE); /* this sets up board[0], but also other stuff */
DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
}
static int loggedOn = FALSE;
/*-- Game start info cache: --*/
int gs_gamenum;
char gs_kind[MSG_SIZ];
static char player1Name[128] = "";
static char player2Name[128] = "";
static char cont_seq[] = "\n\\ ";
static int player1Rating = -1;
static int player2Rating = -1;
/*----------------------------*/
ColorClass curColor = ColorNormal;
int suppressKibitz = 0;
// [HGM] seekgraph
Boolean soughtPending = FALSE;
Boolean seekGraphUp;
#define MAX_SEEK_ADS 200
#define SQUARE 0x80
char *seekAdList[MAX_SEEK_ADS];
int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
float tcList[MAX_SEEK_ADS];
char colorList[MAX_SEEK_ADS];
int nrOfSeekAds = 0;
int minRating = 1010, maxRating = 2800;
int hMargin = 10, vMargin = 20, h, w;
extern int squareSize, lineGap;
void
PlotSeekAd (int i)
{
int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
if(r < minRating+100 && r >=0 ) r = minRating+100;
if(r > maxRating) r = maxRating;
if(tc < 1.f) tc = 1.f;
if(tc > 95.f) tc = 95.f;
x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
y = ((double)r - minRating)/(maxRating - minRating)
* (h-vMargin-squareSize/8-1) + vMargin;
if(ratingList[i] < 0) y = vMargin + squareSize/4;
if(strstr(seekAdList[i], " u ")) color = 1;
if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
!strstr(seekAdList[i], "bullet") &&
!strstr(seekAdList[i], "blitz") &&
!strstr(seekAdList[i], "standard") ) color = 2;
if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
}
void
PlotSingleSeekAd (int i)
{
PlotSeekAd(i);
}
void
AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
{
char buf[MSG_SIZ], *ext = "";
VariantClass v = StringToVariant(type);
if(strstr(type, "wild")) {
ext = type + 4; // append wild number
if(v == VariantFischeRandom) type = "chess960"; else
if(v == VariantLoadable) type = "setup"; else
type = VariantName(v);
}
snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
if(nrOfSeekAds < MAX_SEEK_ADS-1) {
if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
tcList[nrOfSeekAds] = base + (2./3.)*inc;
seekNrList[nrOfSeekAds] = nr;
zList[nrOfSeekAds] = 0;
seekAdList[nrOfSeekAds++] = StrSave(buf);
if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
}
}
void
EraseSeekDot (int i)
{
int x = xList[i], y = yList[i], d=squareSize/4, k;
DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
// now replot every dot that overlapped
for(k=0; k<nrOfSeekAds; k++) if(k != i) {
int xx = xList[k], yy = yList[k];
if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
DrawSeekDot(xx, yy, colorList[k]);
}
}
void
RemoveSeekAd (int nr)
{
int i;
for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
EraseSeekDot(i);
if(seekAdList[i]) free(seekAdList[i]);
seekAdList[i] = seekAdList[--nrOfSeekAds];
seekNrList[i] = seekNrList[nrOfSeekAds];
ratingList[i] = ratingList[nrOfSeekAds];
colorList[i] = colorList[nrOfSeekAds];
tcList[i] = tcList[nrOfSeekAds];
xList[i] = xList[nrOfSeekAds];
yList[i] = yList[nrOfSeekAds];
zList[i] = zList[nrOfSeekAds];
seekAdList[nrOfSeekAds] = NULL;
break;
}
}
Boolean
MatchSoughtLine (char *line)
{
char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
int nr, base, inc, u=0; char dummy;
if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
(u=1) &&
(sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
// match: compact and save the line
AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
return TRUE;
}
return FALSE;
}
int
DrawSeekGraph ()
{
int i;
if(!seekGraphUp) return FALSE;
h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap + 2*border;
w = BOARD_WIDTH * (squareSize + lineGap) + lineGap + 2*border;
DrawSeekBackground(0, 0, w, h);
DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
yy = h-1-yy;
DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
if(i%500 == 0) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "%d", i);
DrawSeekText(buf, hMargin+squareSize/8+7, yy);
}
}
DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
for(i=1; i<100; i+=(i<10?1:5)) {
int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "%d", i);
DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
}
}
for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
return TRUE;
}
int
SeekGraphClick (ClickType click, int x, int y, int moving)
{
static int lastDown = 0, displayed = 0, lastSecond;
if(y < 0) return FALSE;
if(!(appData.seekGraph && appData.icsActive && loggedOn &&
(gameMode == BeginningOfGame || gameMode == IcsIdle))) {
if(!seekGraphUp) return FALSE;
seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
DrawPosition(TRUE, NULL);
return TRUE;
}
if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
if(click == Release || moving) return FALSE;
nrOfSeekAds = 0;
soughtPending = TRUE;
SendToICS(ics_prefix);
SendToICS("sought\n"); // should this be "sought all"?
} else { // issue challenge based on clicked ad
int dist = 10000; int i, closest = 0, second = 0;
for(i=0; i<nrOfSeekAds; i++) {
int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
if(d < dist) { dist = d; closest = i; }
second += (d - zList[i] < 120); // count in-range ads
if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
}
if(dist < 120) {
char buf[MSG_SIZ];
second = (second > 1);
if(displayed != closest || second != lastSecond) {
DisplayMessage(second ? "!" : "", seekAdList[closest]);
lastSecond = second; displayed = closest;
}
if(click == Press) {
if(moving == 2) zList[closest] = 100; // right-click; push to back on press
lastDown = closest;
return TRUE;
} // on press 'hit', only show info
if(moving == 2) return TRUE; // ignore right up-clicks on dot
snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
SendToICS(ics_prefix);
SendToICS(buf);
return TRUE; // let incoming board of started game pop down the graph
} else if(click == Release) { // release 'miss' is ignored
zList[lastDown] = 100; // make future selection of the rejected ad more difficult
if(moving == 2) { // right up-click
nrOfSeekAds = 0; // refresh graph
soughtPending = TRUE;
SendToICS(ics_prefix);
SendToICS("sought\n"); // should this be "sought all"?
}
return TRUE;
} else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
// press miss or release hit 'pop down' seek graph
seekGraphUp = FALSE;
DrawPosition(TRUE, NULL);
}
return TRUE;
}
void
read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
{
#define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
#define STARTED_NONE 0
#define STARTED_MOVES 1
#define STARTED_BOARD 2
#define STARTED_OBSERVE 3
#define STARTED_HOLDINGS 4
#define STARTED_CHATTER 5
#define STARTED_COMMENT 6
#define STARTED_MOVES_NOHIDE 7
static int started = STARTED_NONE;
static char parse[20000];
static int parse_pos = 0;
static char buf[BUF_SIZE + 1];
static int firstTime = TRUE, intfSet = FALSE;
static ColorClass prevColor = ColorNormal;
static int savingComment = FALSE;
static int cmatch = 0; // continuation sequence match
char *bp;
char str[MSG_SIZ];
int i, oldi;
int buf_len;
int next_out;
int tkind;
int backup; /* [DM] For zippy color lines */
char *p;
char talker[MSG_SIZ]; // [HGM] chat
int channel, collective=0;
connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
if (appData.debugMode) {
if (!error) {
fprintf(debugFP, "<ICS: ");
show_bytes(debugFP, data, count);
fprintf(debugFP, "\n");
}
}
if (appData.debugMode) { int f = forwardMostMove;
fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
}
if (count > 0) {
/* If last read ended with a partial line that we couldn't parse,
prepend it to the new read and try again. */
if (leftover_len > 0) {
for (i=0; i<leftover_len; i++)
buf[i] = buf[leftover_start + i];
}
/* copy new characters into the buffer */
bp = buf + leftover_len;
buf_len=leftover_len;
for (i=0; i<count; i++)
{
// ignore these
if (data[i] == '\r')
continue;
// join lines split by ICS?
if (!appData.noJoin)
{
/*
Joining just consists of finding matches against the
continuation sequence, and discarding that sequence
if found instead of copying it. So, until a match
fails, there's nothing to do since it might be the
complete sequence, and thus, something we don't want
copied.
*/
if (data[i] == cont_seq[cmatch])
{
cmatch++;
if (cmatch == strlen(cont_seq))
{
cmatch = 0; // complete match. just reset the counter
/*
it's possible for the ICS to not include the space
at the end of the last word, making our [correct]
join operation fuse two separate words. the server
does this when the space occurs at the width setting.
*/
if (!buf_len || buf[buf_len-1] != ' ')
{
*bp++ = ' ';
buf_len++;
}
}
continue;
}
else if (cmatch)
{
/*
match failed, so we have to copy what matched before
falling through and copying this character. In reality,
this will only ever be just the newline character, but
it doesn't hurt to be precise.
*/
strncpy(bp, cont_seq, cmatch);
bp += cmatch;
buf_len += cmatch;
cmatch = 0;
}
}
// copy this char
*bp++ = data[i];
buf_len++;
}
buf[buf_len] = NULLCHAR;
// next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
next_out = 0;
leftover_start = 0;
i = 0;
while (i < buf_len) {
/* Deal with part of the TELNET option negotiation
protocol. We refuse to do anything beyond the
defaults, except that we allow the WILL ECHO option,
which ICS uses to turn off password echoing when we are
directly connected to it. We reject this option
if localLineEditing mode is on (always on in xboard)
and we are talking to port 23, which might be a real
telnet server that will try to keep WILL ECHO on permanently.
*/
if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
static int remoteEchoOption = FALSE; /* telnet ECHO option */
unsigned char option;
oldi = i;
switch ((unsigned char) buf[++i]) {
case TN_WILL:
if (appData.debugMode)
fprintf(debugFP, "\n<WILL ");
switch (option = (unsigned char) buf[++i]) {
case TN_ECHO:
if (appData.debugMode)
fprintf(debugFP, "ECHO ");
/* Reply only if this is a change, according
to the protocol rules. */
if (remoteEchoOption) break;
if (appData.localLineEditing &&
atoi(appData.icsPort) == TN_PORT) {
TelnetRequest(TN_DONT, TN_ECHO);
} else {
EchoOff();
TelnetRequest(TN_DO, TN_ECHO);
remoteEchoOption = TRUE;
}
break;
default:
if (appData.debugMode)
fprintf(debugFP, "%d ", option);
/* Whatever this is, we don't want it. */
TelnetRequest(TN_DONT, option);
break;
}
break;
case TN_WONT:
if (appData.debugMode)
fprintf(debugFP, "\n<WONT ");
switch (option = (unsigned char) buf[++i]) {
case TN_ECHO:
if (appData.debugMode)
fprintf(debugFP, "ECHO ");
/* Reply only if this is a change, according
to the protocol rules. */
if (!remoteEchoOption) break;
EchoOn();
TelnetRequest(TN_DONT, TN_ECHO);
remoteEchoOption = FALSE;
break;
default:
if (appData.debugMode)
fprintf(debugFP, "%d ", (unsigned char) option);
/* Whatever this is, it must already be turned
off, because we never agree to turn on
anything non-default, so according to the
protocol rules, we don't reply. */
break;
}
break;
case TN_DO:
if (appData.debugMode)
fprintf(debugFP, "\n<DO ");
switch (option = (unsigned char) buf[++i]) {
default:
/* Whatever this is, we refuse to do it. */
if (appData.debugMode)
fprintf(debugFP, "%d ", option);
TelnetRequest(TN_WONT, option);
break;
}
break;
case TN_DONT:
if (appData.debugMode)
fprintf(debugFP, "\n<DONT ");
switch (option = (unsigned char) buf[++i]) {
default:
if (appData.debugMode)
fprintf(debugFP, "%d ", option);
/* Whatever this is, we are already not doing
it, because we never agree to do anything
non-default, so according to the protocol
rules, we don't reply. */
break;
}
break;
case TN_IAC:
if (appData.debugMode)
fprintf(debugFP, "\n<IAC ");
/* Doubled IAC; pass it through */
i--;
break;
default:
if (appData.debugMode)
fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
/* Drop all other telnet commands on the floor */
break;
}
if (oldi > next_out)
SendToPlayer(&buf[next_out], oldi - next_out);
if (++i > next_out)
next_out = i;
continue;
}
/* OK, this at least will *usually* work */
if (!loggedOn && looking_at(buf, &i, "ics%")) {
loggedOn = TRUE;
}
if (loggedOn && !intfSet) {
if (ics_type == ICS_ICC) {
snprintf(str, MSG_SIZ,
"/set-quietly interface %s\n/set-quietly style 12\n",
programVersion);
if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
strcat(str, "/set-2 51 1\n/set seek 1\n");
} else if (ics_type == ICS_CHESSNET) {
snprintf(str, MSG_SIZ, "/style 12\n");
} else {
safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
strcat(str, programVersion);
strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
strcat(str, "$iset seekremove 1\n$set seek 1\n");
#ifdef WIN32
strcat(str, "$iset nohighlight 1\n");
#endif
strcat(str, "$iset lock 1\n$style 12\n");
}
SendToICS(str);
NotifyFrontendLogin();
intfSet = TRUE;
}
if (started == STARTED_COMMENT) {
/* Accumulate characters in comment */
parse[parse_pos++] = buf[i];
if (buf[i] == '\n') {
parse[parse_pos] = NULLCHAR;
if(chattingPartner>=0) {
char mess[MSG_SIZ];
snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
OutputChatMessage(chattingPartner, mess);
if(collective == 1) { // broadcasted talk also goes to private chatbox of talker
int p;
talker[strlen(talker+1)-1] = NULLCHAR; // strip closing delimiter
for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
snprintf(mess, MSG_SIZ, "%s: %s", chatPartner[chattingPartner], parse);
OutputChatMessage(p, mess);
break;
}
}
chattingPartner = -1;
if(collective != 3) next_out = i+1; // [HGM] suppress printing in ICS window
collective = 0;
} else
if(!suppressKibitz) // [HGM] kibitz
AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
int nrDigit = 0, nrAlph = 0, j;
if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
{ parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
parse[parse_pos] = NULLCHAR;
// try to be smart: if it does not look like search info, it should go to
// ICS interaction window after all, not to engine-output window.
for(j=0; j<parse_pos; j++) { // count letters and digits
nrDigit += (parse[j] >= '0' && parse[j] <= '9');
nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
}
if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
int depth=0; float score;
if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
// [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
pvInfoList[forwardMostMove-1].depth = depth;
pvInfoList[forwardMostMove-1].score = 100*score;
}
OutputKibitz(suppressKibitz, parse);
} else {
char tmp[MSG_SIZ];
if(gameMode == IcsObserving) // restore original ICS messages
/* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
else
/* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
SendToPlayer(tmp, strlen(tmp));
}
next_out = i+1; // [HGM] suppress printing in ICS window
}
started = STARTED_NONE;
} else {
/* Don't match patterns against characters in comment */
i++;
continue;
}
}
if (started == STARTED_CHATTER) {
if (buf[i] != '\n') {
/* Don't match patterns against characters in chatter */
i++;
continue;
}
started = STARTED_NONE;
if(suppressKibitz) next_out = i+1;
}
/* Kludge to deal with rcmd protocol */
if (firstTime && looking_at(buf, &i, "\001*")) {
DisplayFatalError(&buf[1], 0, 1);
continue;
} else {
firstTime = FALSE;
}
if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
ics_type = ICS_ICC;
ics_prefix = "/";
if (appData.debugMode)
fprintf(debugFP, "ics_type %d\n", ics_type);
continue;
}
if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
ics_type = ICS_FICS;
ics_prefix = "$";
if (appData.debugMode)
fprintf(debugFP, "ics_type %d\n", ics_type);
continue;
}
if (!loggedOn && looking_at(buf, &i, "chess.net")) {
ics_type = ICS_CHESSNET;
ics_prefix = "/";
if (appData.debugMode)
fprintf(debugFP, "ics_type %d\n", ics_type);
continue;
}
if (!loggedOn &&
(looking_at(buf, &i, "\"*\" is *a registered name") ||
looking_at(buf, &i, "Logging you in as \"*\"") ||
looking_at(buf, &i, "will be \"*\""))) {
safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
continue;
}
if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
char buf[MSG_SIZ];
snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
DisplayIcsInteractionTitle(buf);
have_set_title = TRUE;
}
/* skip finger notes */
if (started == STARTED_NONE &&
((buf[i] == ' ' && isdigit(buf[i+1])) ||
(buf[i] == '1' && buf[i+1] == '0')) &&
buf[i+2] == ':' && buf[i+3] == ' ') {
started = STARTED_CHATTER;
i += 3;
continue;
}
oldi = i;
// [HGM] seekgraph: recognize sought lines and end-of-sought message
if(appData.seekGraph) {
if(soughtPending && MatchSoughtLine(buf+i)) {
i = strstr(buf+i, "rated") - buf;
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
next_out = leftover_start = i;
started = STARTED_CHATTER;
suppressKibitz = TRUE;
continue;
}
if((gameMode == IcsIdle || gameMode == BeginningOfGame)
&& looking_at(buf, &i, "* ads displayed")) {
soughtPending = FALSE;
seekGraphUp = TRUE;
DrawSeekGraph();
continue;
}
if(appData.autoRefresh) {
if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
int s = (ics_type == ICS_ICC); // ICC format differs
if(seekGraphUp)
AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
looking_at(buf, &i, "*% "); // eat prompt
if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
next_out = i; // suppress
continue;
}
if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
char *p = star_match[0];
while(*p) {
if(seekGraphUp) RemoveSeekAd(atoi(p));
while(*p && *p++ != ' '); // next
}
looking_at(buf, &i, "*% "); // eat prompt
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
next_out = i;
continue;
}
}
}
/* skip formula vars */
if (started == STARTED_NONE &&
buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
started = STARTED_CHATTER;
i += 3;
continue;
}
// [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
if (appData.autoKibitz && started == STARTED_NONE &&
!appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
(gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
(StrStr(star_match[0], gameInfo.white) == star_match[0] ||
StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
suppressKibitz = TRUE;
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
next_out = i;
if((StrStr(star_match[0], gameInfo.white) == star_match[0]
&& (gameMode == IcsPlayingWhite)) ||
(StrStr(star_match[0], gameInfo.black) == star_match[0]
&& (gameMode == IcsPlayingBlack)) ) // opponent kibitz
started = STARTED_CHATTER; // own kibitz we simply discard
else {
started = STARTED_COMMENT; // make sure it will be collected in parse[]
parse_pos = 0; parse[0] = NULLCHAR;
savingComment = TRUE;
suppressKibitz = gameMode != IcsObserving ? 2 :
(StrStr(star_match[0], gameInfo.white) == NULL) + 1;
}
continue;
} else
if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
&& atoi(star_match[0])) {
// suppress the acknowledgements of our own autoKibitz
char *p;
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
SendToPlayer(star_match[0], strlen(star_match[0]));
if(looking_at(buf, &i, "*% ")) // eat prompt
suppressKibitz = FALSE;
next_out = i;
continue;
}
} // [HGM] kibitz: end of patch
if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
// [HGM] chat: intercept tells by users for which we have an open chat window
channel = -1;
if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
looking_at(buf, &i, "* whispers:") ||
looking_at(buf, &i, "* kibitzes:") ||
looking_at(buf, &i, "* shouts:") ||
looking_at(buf, &i, "* c-shouts:") ||
looking_at(buf, &i, "--> * ") ||
looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
int p;
sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
chattingPartner = -1; collective = 0;
if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
for(p=0; p<MAX_CHAT; p++) {
collective = 1;
if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
talker[0] = '['; strcat(talker, "] ");
Colorize((channel == 1 ? ColorChannel1 : ColorChannel), FALSE);
chattingPartner = p; break;
}
} else
if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
for(p=0; p<MAX_CHAT; p++) {
collective = 1;
if(!strcmp("kibitzes", chatPartner[p])) {
talker[0] = '['; strcat(talker, "] ");
chattingPartner = p; break;
}
} else
if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
for(p=0; p<MAX_CHAT; p++) {
collective = 1;
if(!strcmp("whispers", chatPartner[p])) {
talker[0] = '['; strcat(talker, "] ");
chattingPartner = p; break;
}
} else
if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
if(buf[i-8] == '-' && buf[i-3] == 't')
for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
collective = 1;
if(!strcmp("c-shouts", chatPartner[p])) {
talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
chattingPartner = p; break;
}
}
if(chattingPartner < 0)
for(p=0; p<MAX_CHAT; p++) {
collective = 1;
if(!strcmp("shouts", chatPartner[p])) {
if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
chattingPartner = p; break;
}
}
}
if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
talker[0] = 0;
Colorize(ColorTell, FALSE);
if(collective) safeStrCpy(talker, "broadcasts: ", MSG_SIZ);
collective |= 2;
chattingPartner = p; break;
}
if(chattingPartner<0) i = oldi, safeStrCpy(lastTalker, talker+1, MSG_SIZ); else {
Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
started = STARTED_COMMENT;
parse_pos = 0; parse[0] = NULLCHAR;
savingComment = 3 + chattingPartner; // counts as TRUE
if(collective == 3) i = oldi; else {
suppressKibitz = TRUE;
if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
continue;
}
}
} // [HGM] chat: end of patch
backup = i;
if (appData.zippyTalk || appData.zippyPlay) {
/* [DM] Backup address for color zippy lines */
#if ZIPPY
if (loggedOn == TRUE)
if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
(appData.zippyPlay && ZippyMatch(buf, &backup)))
;
#endif
} // [DM] 'else { ' deleted
if (
/* Regular tells and says */
(tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
looking_at(buf, &i, "* (your partner) tells you: ") ||
looking_at(buf, &i, "* says: ") ||
/* Don't color "message" or "messages" output */
(tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
looking_at(buf, &i, "*. * at *:*: ") ||
looking_at(buf, &i, "--* (*:*): ") ||
/* Message notifications (same color as tells) */
looking_at(buf, &i, "* has left a message ") ||
looking_at(buf, &i, "* just sent you a message:\n") ||
/* Whispers and kibitzes */
(tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
looking_at(buf, &i, "* kibitzes: ") ||
/* Channel tells */
(tkind = 3, looking_at(buf, &i, "*(*: "))) {
if (tkind == 1 && strchr(star_match[0], ':')) {
/* Avoid "tells you:" spoofs in channels */
tkind = 3;
}
if (star_match[0][0] == NULLCHAR ||
strchr(star_match[0], ' ') ||
(tkind == 3 && strchr(star_match[1], ' '))) {
/* Reject bogus matches */
i = oldi;
} else {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
switch (tkind) {
case 1:
Colorize(ColorTell, FALSE);
curColor = ColorTell;
break;
case 2:
Colorize(ColorKibitz, FALSE);
curColor = ColorKibitz;
break;
case 3:
p = strrchr(star_match[1], '(');
if (p == NULL) {
p = star_match[1];
} else {
p++;
}
if (atoi(p) == 1) {
Colorize(ColorChannel1, FALSE);
curColor = ColorChannel1;
} else {
Colorize(ColorChannel, FALSE);
curColor = ColorChannel;
}
break;
case 5:
curColor = ColorNormal;
break;
}
}
if (started == STARTED_NONE && appData.autoComment &&
(gameMode == IcsObserving ||
gameMode == IcsPlayingWhite ||
gameMode == IcsPlayingBlack)) {
parse_pos = i - oldi;
memcpy(parse, &buf[oldi], parse_pos);
parse[parse_pos] = NULLCHAR;
started = STARTED_COMMENT;
savingComment = TRUE;
} else if(collective != 3) {
started = STARTED_CHATTER;
savingComment = FALSE;
}
loggedOn = TRUE;
continue;
}
}
if (looking_at(buf, &i, "* s-shouts: ") ||
looking_at(buf, &i, "* c-shouts: ")) {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorSShout, FALSE);
curColor = ColorSShout;
}
loggedOn = TRUE;
started = STARTED_CHATTER;
continue;
}
if (looking_at(buf, &i, "--->")) {
loggedOn = TRUE;
continue;
}
if (looking_at(buf, &i, "* shouts: ") ||
looking_at(buf, &i, "--> ")) {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorShout, FALSE);
curColor = ColorShout;
}
loggedOn = TRUE;
started = STARTED_CHATTER;
continue;
}
if (looking_at( buf, &i, "Challenge:")) {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorChallenge, FALSE);
curColor = ColorChallenge;
}
loggedOn = TRUE;
continue;
}
if (looking_at(buf, &i, "* offers you") ||
looking_at(buf, &i, "* offers to be") ||
looking_at(buf, &i, "* would like to") ||
looking_at(buf, &i, "* requests to") ||
looking_at(buf, &i, "Your opponent offers") ||
looking_at(buf, &i, "Your opponent requests")) {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorRequest, FALSE);
curColor = ColorRequest;
}
continue;
}
if (looking_at(buf, &i, "* (*) seeking")) {
if (appData.colorize) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorSeek, FALSE);
curColor = ColorSeek;
}
continue;
}
if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
if (looking_at(buf, &i, "\\ ")) {
if (prevColor != ColorNormal) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(prevColor, TRUE);
curColor = prevColor;
}
if (savingComment) {
parse_pos = i - oldi;
memcpy(parse, &buf[oldi], parse_pos);
parse[parse_pos] = NULLCHAR;
started = STARTED_COMMENT;
if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
chattingPartner = savingComment - 3; // kludge to remember the box
} else {
started = STARTED_CHATTER;
}
continue;
}
if (looking_at(buf, &i, "Black Strength :") ||
looking_at(buf, &i, "<<< style 10 board >>>") ||
looking_at(buf, &i, "<10>") ||
looking_at(buf, &i, "#@#")) {
/* Wrong board style */
loggedOn = TRUE;
SendToICS(ics_prefix);
SendToICS("set style 12\n");
SendToICS(ics_prefix);
SendToICS("refresh\n");
continue;
}
if (looking_at(buf, &i, "login:")) {
if (!have_sent_ICS_logon) {
if(ICSInitScript())
have_sent_ICS_logon = 1;
else // no init script was found
have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
} else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
}
continue;
}
if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
(looking_at(buf, &i, "\n<12> ") ||
looking_at(buf, &i, "<12> "))) {
loggedOn = TRUE;
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
}
next_out = i;
started = STARTED_BOARD;
parse_pos = 0;
continue;
}
if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
looking_at(buf, &i, "<b1> ")) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
}
next_out = i;
started = STARTED_HOLDINGS;
parse_pos = 0;
continue;
}
if (looking_at(buf, &i, "* *vs. * *--- *")) {
loggedOn = TRUE;
/* Header for a move list -- first line */
switch (ics_getting_history) {
case H_FALSE:
switch (gameMode) {
case IcsIdle:
case BeginningOfGame:
/* User typed "moves" or "oldmoves" while we
were idle. Pretend we asked for these
moves and soak them up so user can step
through them and/or save them.
*/
Reset(FALSE, TRUE);
gameMode = IcsObserving;
ModeHighlight();
ics_gamenum = -1;
ics_getting_history = H_GOT_UNREQ_HEADER;
break;
case EditGame: /*?*/
case EditPosition: /*?*/
/* Should above feature work in these modes too? */
/* For now it doesn't */
ics_getting_history = H_GOT_UNWANTED_HEADER;
break;
default:
ics_getting_history = H_GOT_UNWANTED_HEADER;
break;
}
break;
case H_REQUESTED:
/* Is this the right one? */
if (gameInfo.white && gameInfo.black &&
strcmp(gameInfo.white, star_match[0]) == 0 &&
strcmp(gameInfo.black, star_match[2]) == 0) {
/* All is well */
ics_getting_history = H_GOT_REQ_HEADER;
}
break;
case H_GOT_REQ_HEADER:
case H_GOT_UNREQ_HEADER:
case H_GOT_UNWANTED_HEADER:
case H_GETTING_MOVES:
/* Should not happen */
DisplayError(_("Error gathering move list: two headers"), 0);
ics_getting_history = H_FALSE;
break;
}
/* Save player ratings into gameInfo if needed */
if ((ics_getting_history == H_GOT_REQ_HEADER ||
ics_getting_history == H_GOT_UNREQ_HEADER) &&
(gameInfo.whiteRating == -1 ||
gameInfo.blackRating == -1)) {
gameInfo.whiteRating = string_to_rating(star_match[1]);
gameInfo.blackRating = string_to_rating(star_match[3]);
if (appData.debugMode)
fprintf(debugFP, "Ratings from header: W %d, B %d\n",
gameInfo.whiteRating, gameInfo.blackRating);
}
continue;
}
if (looking_at(buf, &i,
"* * match, initial time: * minute*, increment: * second")) {
/* Header for a move list -- second line */
/* Initial board will follow if this is a wild game */
if (gameInfo.event != NULL) free(gameInfo.event);
snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
gameInfo.event = StrSave(str);
/* [HGM] we switched variant. Translate boards if needed. */
VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
continue;
}
if (looking_at(buf, &i, "Move ")) {
/* Beginning of a move list */
switch (ics_getting_history) {
case H_FALSE:
/* Normally should not happen */
/* Maybe user hit reset while we were parsing */
break;
case H_REQUESTED:
/* Happens if we are ignoring a move list that is not
* the one we just requested. Common if the user
* tries to observe two games without turning off
* getMoveList */
break;
case H_GETTING_MOVES:
/* Should not happen */
DisplayError(_("Error gathering move list: nested"), 0);
ics_getting_history = H_FALSE;
break;
case H_GOT_REQ_HEADER:
ics_getting_history = H_GETTING_MOVES;
started = STARTED_MOVES;
parse_pos = 0;
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
}
break;
case H_GOT_UNREQ_HEADER:
ics_getting_history = H_GETTING_MOVES;
started = STARTED_MOVES_NOHIDE;
parse_pos = 0;
break;
case H_GOT_UNWANTED_HEADER:
ics_getting_history = H_FALSE;
break;
}
continue;
}
if (looking_at(buf, &i, "% ") ||
((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
&& looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
soughtPending = FALSE;
seekGraphUp = TRUE;
DrawSeekGraph();
}
if(suppressKibitz) next_out = i;
savingComment = FALSE;
suppressKibitz = 0;
switch (started) {
case STARTED_MOVES:
case STARTED_MOVES_NOHIDE:
memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
parse[parse_pos + i - oldi] = NULLCHAR;
ParseGameHistory(parse);
#if ZIPPY
if (appData.zippyPlay && first.initDone) {
FeedMovesToProgram(&first, forwardMostMove);
if (gameMode == IcsPlayingWhite) {
if (WhiteOnMove(forwardMostMove)) {
if (first.sendTime) {
if (first.useColors) {
SendToProgram("black\n", &first);
}
SendTimeRemaining(&first, TRUE);
}
if (first.useColors) {
SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
}
bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
first.maybeThinking = TRUE;
} else {
if (first.usePlayother) {
if (first.sendTime) {
SendTimeRemaining(&first, TRUE);
}
SendToProgram("playother\n", &first);
firstMove = FALSE;
} else {
firstMove = TRUE;
}
}
} else if (gameMode == IcsPlayingBlack) {
if (!WhiteOnMove(forwardMostMove)) {
if (first.sendTime) {
if (first.useColors) {
SendToProgram("white\n", &first);
}
SendTimeRemaining(&first, FALSE);
}
if (first.useColors) {
SendToProgram("black\n", &first);
}
bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
first.maybeThinking = TRUE;
} else {
if (first.usePlayother) {
if (first.sendTime) {
SendTimeRemaining(&first, FALSE);
}
SendToProgram("playother\n", &first);
firstMove = FALSE;
} else {
firstMove = TRUE;
}
}
}
}
#endif
if (gameMode == IcsObserving && ics_gamenum == -1) {
/* Moves came from oldmoves or moves command
while we weren't doing anything else.
*/
currentMove = forwardMostMove;
ClearHighlights();/*!!could figure this out*/
flipView = appData.flipView;
DrawPosition(TRUE, boards[currentMove]);
DisplayBothClocks();
snprintf(str, MSG_SIZ, "%s %s %s",
gameInfo.white, _("vs."), gameInfo.black);
DisplayTitle(str);
gameMode = IcsIdle;
} else {
/* Moves were history of an active game */
if (gameInfo.resultDetails != NULL) {
free(gameInfo.resultDetails);
gameInfo.resultDetails = NULL;
}
}
HistorySet(parseList, backwardMostMove,
forwardMostMove, currentMove-1);
DisplayMove(currentMove - 1);
if (started == STARTED_MOVES) next_out = i;
started = STARTED_NONE;
ics_getting_history = H_FALSE;
break;
case STARTED_OBSERVE:
started = STARTED_NONE;
SendToICS(ics_prefix);
SendToICS("refresh\n");
break;
default:
break;
}
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
HandleMachineMove(bookMove, &first);
}
continue;
}
if ((started == STARTED_MOVES || started == STARTED_BOARD ||
started == STARTED_HOLDINGS ||
started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
/* Accumulate characters in move list or board */
parse[parse_pos++] = buf[i];
}
/* Start of game messages. Mostly we detect start of game
when the first board image arrives. On some versions
of the ICS, though, we need to do a "refresh" after starting
to observe in order to get the current board right away. */
if (looking_at(buf, &i, "Adding game * to observation list")) {
started = STARTED_OBSERVE;
continue;
}
/* Handle auto-observe */
if (appData.autoObserve &&
(gameMode == IcsIdle || gameMode == BeginningOfGame) &&
looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
char *player;
/* Choose the player that was highlighted, if any. */
if (star_match[0][0] == '\033' ||
star_match[1][0] != '\033') {
player = star_match[0];
} else {
player = star_match[2];
}
snprintf(str, MSG_SIZ, "%sobserve %s\n",
ics_prefix, StripHighlightAndTitle(player));
SendToICS(str);
/* Save ratings from notify string */
safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
player1Rating = string_to_rating(star_match[1]);
safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
player2Rating = string_to_rating(star_match[3]);
if (appData.debugMode)
fprintf(debugFP,
"Ratings from 'Game notification:' %s %d, %s %d\n",
player1Name, player1Rating,
player2Name, player2Rating);
continue;
}
/* Deal with automatic examine mode after a game,
and with IcsObserving -> IcsExamining transition */
if (looking_at(buf, &i, "Entering examine mode for game *") ||
looking_at(buf, &i, "has made you an examiner of game *")) {
int gamenum = atoi(star_match[0]);
if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
gamenum == ics_gamenum) {
/* We were already playing or observing this game;
no need to refetch history */
gameMode = IcsExamining;
if (pausing) {
pauseExamForwardMostMove = forwardMostMove;
} else if (currentMove < forwardMostMove) {
ForwardInner(forwardMostMove);
}
} else {
/* I don't think this case really can happen */
SendToICS(ics_prefix);
SendToICS("refresh\n");
}
continue;
}
/* Error messages */
// if (ics_user_moved) {
if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
if (looking_at(buf, &i, "Illegal move") ||
looking_at(buf, &i, "Not a legal move") ||
looking_at(buf, &i, "Your king is in check") ||
looking_at(buf, &i, "It isn't your turn") ||
looking_at(buf, &i, "It is not your move")) {
/* Illegal move */
if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
currentMove = forwardMostMove-1;
DisplayMove(currentMove - 1); /* before DMError */
DrawPosition(FALSE, boards[currentMove]);
SwitchClocks(forwardMostMove-1); // [HGM] race
DisplayBothClocks();
}
DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
ics_user_moved = 0;
continue;
}
}
if (looking_at(buf, &i, "still have time") ||
looking_at(buf, &i, "not out of time") ||
looking_at(buf, &i, "either player is out of time") ||
looking_at(buf, &i, "has timeseal; checking")) {
/* We must have called his flag a little too soon */
whiteFlag = blackFlag = FALSE;
continue;
}
if (looking_at(buf, &i, "added * seconds to") ||
looking_at(buf, &i, "seconds were added to")) {
/* Update the clocks */
SendToICS(ics_prefix);
SendToICS("refresh\n");
continue;
}
if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
ics_clock_paused = TRUE;
StopClocks();
continue;
}
if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
ics_clock_paused = FALSE;
StartClocks();
continue;
}
/* Grab player ratings from the Creating: message.
Note we have to check for the special case when
the ICS inserts things like [white] or [black]. */
if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
/* star_matches:
0 player 1 name (not necessarily white)
1 player 1 rating
2 empty, white, or black (IGNORED)
3 player 2 name (not necessarily black)
4 player 2 rating
The names/ratings are sorted out when the game
actually starts (below).
*/
safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
player1Rating = string_to_rating(star_match[1]);
safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
player2Rating = string_to_rating(star_match[4]);
if (appData.debugMode)
fprintf(debugFP,
"Ratings from 'Creating:' %s %d, %s %d\n",
player1Name, player1Rating,
player2Name, player2Rating);
continue;
}
/* Improved generic start/end-of-game messages */
if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
(tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
/* If tkind == 0: */
/* star_match[0] is the game number */
/* [1] is the white player's name */
/* [2] is the black player's name */
/* For end-of-game: */
/* [3] is the reason for the game end */
/* [4] is a PGN end game-token, preceded by " " */
/* For start-of-game: */
/* [3] begins with "Creating" or "Continuing" */
/* [4] is " *" or empty (don't care). */
int gamenum = atoi(star_match[0]);
char *whitename, *blackname, *why, *endtoken;
ChessMove endtype = EndOfFile;
if (tkind == 0) {
whitename = star_match[1];
blackname = star_match[2];
why = star_match[3];
endtoken = star_match[4];
} else {
whitename = star_match[1];
blackname = star_match[3];
why = star_match[5];
endtoken = star_match[6];
}
/* Game start messages */
if (strncmp(why, "Creating ", 9) == 0 ||
strncmp(why, "Continuing ", 11) == 0) {
gs_gamenum = gamenum;
safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
#if ZIPPY
if (appData.zippyPlay) {
ZippyGameStart(whitename, blackname);
}
#endif /*ZIPPY*/
partnerBoardValid = FALSE; // [HGM] bughouse
continue;
}
/* Game end messages */
if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
ics_gamenum != gamenum) {
continue;
}
while (endtoken[0] == ' ') endtoken++;
switch (endtoken[0]) {
case '*':
default:
endtype = GameUnfinished;
break;
case '0':
endtype = BlackWins;
break;
case '1':
if (endtoken[1] == '/')
endtype = GameIsDrawn;
else
endtype = WhiteWins;
break;
}
GameEnds(endtype, why, GE_ICS);
#if ZIPPY
if (appData.zippyPlay && first.initDone) {
ZippyGameEnd(endtype, why);
if (first.pr == NoProc) {
/* Start the next process early so that we'll
be ready for the next challenge */
StartChessProgram(&first);
}
/* Send "new" early, in case this command takes
a long time to finish, so that we'll be ready
for the next challenge. */
gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
Reset(TRUE, TRUE);
}
#endif /*ZIPPY*/
if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
continue;
}
if (looking_at(buf, &i, "Removing game * from observation") ||
looking_at(buf, &i, "no longer observing game *") ||
looking_at(buf, &i, "Game * (*) has no examiners")) {
if (gameMode == IcsObserving &&
atoi(star_match[0]) == ics_gamenum)
{
/* icsEngineAnalyze */
if (appData.icsEngineAnalyze) {
ExitAnalyzeMode();
ModeHighlight();
}
StopClocks();
gameMode = IcsIdle;
ics_gamenum = -1;
ics_user_moved = FALSE;
}
continue;
}
if (looking_at(buf, &i, "no longer examining game *")) {
if (gameMode == IcsExamining &&
atoi(star_match[0]) == ics_gamenum)
{
gameMode = IcsIdle;
ics_gamenum = -1;
ics_user_moved = FALSE;
}
continue;
}
/* Advance leftover_start past any newlines we find,
so only partial lines can get reparsed */
if (looking_at(buf, &i, "\n")) {
prevColor = curColor;
if (curColor != ColorNormal) {
if (oldi > next_out) {
SendToPlayer(&buf[next_out], oldi - next_out);
next_out = oldi;
}
Colorize(ColorNormal, FALSE);
curColor = ColorNormal;
}
if (started == STARTED_BOARD) {
started = STARTED_NONE;
parse[parse_pos] = NULLCHAR;
ParseBoard12(parse);
ics_user_moved = 0;
/* Send premove here */
if (appData.premove) {
char str[MSG_SIZ];
if (currentMove == 0 &&
gameMode == IcsPlayingWhite &&
appData.premoveWhite) {
snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
if (appData.debugMode)
fprintf(debugFP, "Sending premove:\n");
SendToICS(str);
} else if (currentMove == 1 &&
gameMode == IcsPlayingBlack &&
appData.premoveBlack) {
snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
if (appData.debugMode)
fprintf(debugFP, "Sending premove:\n");
SendToICS(str);
} else if (gotPremove) {
int oldFMM = forwardMostMove;
gotPremove = 0;
ClearPremoveHighlights();
if (appData.debugMode)
fprintf(debugFP, "Sending premove:\n");
UserMoveEvent(premoveFromX, premoveFromY,
premoveToX, premoveToY,
premovePromoChar);
if(forwardMostMove == oldFMM) { // premove was rejected, highlight last opponent move
if(moveList[oldFMM-1][1] != '@')
SetHighlights(moveList[oldFMM-1][0]-AAA, moveList[oldFMM-1][1]-ONE,
moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
else // (drop)
SetHighlights(-1, -1, moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
}
}
}
/* Usually suppress following prompt */
if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
if (looking_at(buf, &i, "*% ")) {
savingComment = FALSE;
suppressKibitz = 0;
}
}
next_out = i;
} else if (started == STARTED_HOLDINGS) {
int gamenum;
char new_piece[MSG_SIZ];
started = STARTED_NONE;
parse[parse_pos] = NULLCHAR;
if (appData.debugMode)
fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
parse, currentMove);
if (sscanf(parse, " game %d", &gamenum) == 1) {
if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
if (gameInfo.variant == VariantNormal) {
/* [HGM] We seem to switch variant during a game!
* Presumably no holdings were displayed, so we have
* to move the position two files to the right to
* create room for them!
*/
VariantClass newVariant;
switch(gameInfo.boardWidth) { // base guess on board width
case 9: newVariant = VariantShogi; break;
case 10: newVariant = VariantGreat; break;
default: newVariant = VariantCrazyhouse; break;
}
VariantSwitch(boards[currentMove], newVariant); /* temp guess */
/* Get a move list just to see the header, which
will tell us whether this is really bug or zh */
if (ics_getting_history == H_FALSE) {
ics_getting_history = H_REQUESTED;
snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
SendToICS(str);
}
}
new_piece[0] = NULLCHAR;
sscanf(parse, "game %d white [%s black [%s <- %s",
&gamenum, white_holding, black_holding,
new_piece);
white_holding[strlen(white_holding)-1] = NULLCHAR;
black_holding[strlen(black_holding)-1] = NULLCHAR;
/* [HGM] copy holdings to board holdings area */
CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
#if ZIPPY
if (appData.zippyPlay && first.initDone) {
ZippyHoldings(white_holding, black_holding,
new_piece);
}
#endif /*ZIPPY*/
if (tinyLayout || smallLayout) {
char wh[16], bh[16];
PackHolding(wh, white_holding);
PackHolding(bh, black_holding);
snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
gameInfo.white, gameInfo.black);
} else {
snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
gameInfo.white, white_holding, _("vs."),
gameInfo.black, black_holding);
}
if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
DrawPosition(FALSE, boards[currentMove]);
DisplayTitle(str);
} else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
sscanf(parse, "game %d white [%s black [%s <- %s",
&gamenum, white_holding, black_holding,
new_piece);
white_holding[strlen(white_holding)-1] = NULLCHAR;
black_holding[strlen(black_holding)-1] = NULLCHAR;
/* [HGM] copy holdings to partner-board holdings area */
CopyHoldings(partnerBoard, white_holding, WhitePawn);
CopyHoldings(partnerBoard, black_holding, BlackPawn);
if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
if(partnerUp) DrawPosition(FALSE, partnerBoard);
if(twoBoards) { partnerUp = 0; flipView = !flipView; }
}
}
/* Suppress following prompt */
if (looking_at(buf, &i, "*% ")) {
if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
savingComment = FALSE;
suppressKibitz = 0;
}
next_out = i;
}
continue;
}
i++; /* skip unparsed character and loop back */
}
if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
// started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
// SendToPlayer(&buf[next_out], i - next_out);
started != STARTED_HOLDINGS && leftover_start > next_out) {
SendToPlayer(&buf[next_out], leftover_start - next_out);
next_out = i;
}
leftover_len = buf_len - leftover_start;
/* if buffer ends with something we couldn't parse,
reparse it after appending the next read */
} else if (count == 0) {
RemoveInputSource(isr);
DisplayFatalError(_("Connection closed by ICS"), 0, 6666);
} else {
DisplayFatalError(_("Error reading from ICS"), error, 1);
}
}
/* Board style 12 looks like this:
<12> r-b---k- pp----pp ---bP--- ---p---- q------- ------P- P--Q--BP -----R-K W -1 0 0 0 0 0 0 paf MaxII 0 2 12 21 25 234 174 24 Q/d7-a4 (0:06) Qxa4 0 0
* The "<12> " is stripped before it gets to this routine. The two
* trailing 0's (flip state and clock ticking) are later addition, and
* some chess servers may not have them, or may have only the first.
* Additional trailing fields may be added in the future.
*/
#define PATTERN "%c%d%d%d%d%d%d%d%s%s%d%d%d%d%d%d%d%d%s%s%s%d%d"
#define RELATION_OBSERVING_PLAYED 0
#define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
#define RELATION_PLAYING_MYMOVE 1
#define RELATION_PLAYING_NOTMYMOVE -1
#define RELATION_EXAMINING 2
#define RELATION_ISOLATED_BOARD -3
#define RELATION_STARTING_POSITION -4 /* FICS only */
void
ParseBoard12 (char *string)
{
#if ZIPPY
int i, takeback;
char *bookHit = NULL; // [HGM] book
#endif
GameMode newGameMode;
int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
char to_play, board_chars[200];
char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
char black[32], white[32];
Board board;
int prevMove = currentMove;
int ticking = 2;
ChessMove moveType;
int fromX, fromY, toX, toY;
char promoChar;
int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
Boolean weird = FALSE, reqFlag = FALSE;
fromX = fromY = toX = toY = -1;
newGame = FALSE;
if (appData.debugMode)
fprintf(debugFP, "Parsing board: %s\n", string);
move_str[0] = NULLCHAR;
elapsed_time[0] = NULLCHAR;
{ /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
int i = 0, j;
while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
if(string[i] == ' ') { ranks++; files = 0; }
else files++;
if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
i++;
}
for(j = 0; j <i; j++) board_chars[j] = string[j];
board_chars[i] = '\0';
string += i + 1;
}
n = sscanf(string, PATTERN, &to_play, &double_push,
&castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
&gamenum, white, black, &relation, &basetime, &increment,
&white_stren, &black_stren, &white_time, &black_time,
&moveNum, str, elapsed_time, move_str, &ics_flip,
&ticking);
if (n < 21) {
snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
DisplayError(str, 0);
return;
}
/* Convert the move number to internal form */
moveNum = (moveNum - 1) * 2;
if (to_play == 'B') moveNum++;
if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
0, 1);
return;
}
switch (relation) {
case RELATION_OBSERVING_PLAYED:
case RELATION_OBSERVING_STATIC:
if (gamenum == -1) {
/* Old ICC buglet */
relation = RELATION_OBSERVING_STATIC;
}
newGameMode = IcsObserving;
break;
case RELATION_PLAYING_MYMOVE:
case RELATION_PLAYING_NOTMYMOVE:
newGameMode =
((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
IcsPlayingWhite : IcsPlayingBlack;
soughtPending =FALSE; // [HGM] seekgraph: solve race condition
break;
case RELATION_EXAMINING:
newGameMode = IcsExamining;
break;
case RELATION_ISOLATED_BOARD:
default:
/* Just display this board. If user was doing something else,
we will forget about it until the next board comes. */
newGameMode = IcsIdle;
break;
case RELATION_STARTING_POSITION:
newGameMode = gameMode;
break;
}
if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
&& newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
// [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
int fac = strchr(elapsed_time, '.') ? 1 : 1000;
static int lastBgGame = -1;
char *toSqr;
for (k = 0; k < ranks; k++) {
for (j = 0; j < files; j++)
board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
if(gameInfo.holdingsWidth > 1) {
board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
}
}
CopyBoard(partnerBoard, board);
if(toSqr = strchr(str, '/')) { // extract highlights from long move
partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
} else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
if(toSqr = strchr(str, '-')) {
partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
} else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
if(partnerUp) DrawPosition(FALSE, partnerBoard);
if(twoBoards) {
DisplayWhiteClock(white_time*fac, to_play == 'W');
DisplayBlackClock(black_time*fac, to_play != 'W');
activePartner = to_play;
if(gamenum != lastBgGame) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
DisplayTitle(buf);
}
lastBgGame = gamenum;
activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
partnerUp = 0; flipView = !flipView; } // [HGM] dual
snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
(black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
if(!twoBoards) DisplayMessage(partnerStatus, "");
partnerBoardValid = TRUE;
return;
}
if(appData.dualBoard && appData.bgObserve) {
if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
SendToICS(ics_prefix), SendToICS("pobserve\n");
else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
SendToICS(buf);
}
}
/* Modify behavior for initial board display on move listing
of wild games.
*/
switch (ics_getting_history) {
case H_FALSE:
case H_REQUESTED:
break;
case H_GOT_REQ_HEADER:
case H_GOT_UNREQ_HEADER:
/* This is the initial position of the current game */
gamenum = ics_gamenum;
moveNum = 0; /* old ICS bug workaround */
if (to_play == 'B') {
startedFromSetupPosition = TRUE;
blackPlaysFirst = TRUE;
moveNum = 1;
if (forwardMostMove == 0) forwardMostMove = 1;
if (backwardMostMove == 0) backwardMostMove = 1;
if (currentMove == 0) currentMove = 1;
}
newGameMode = gameMode;
relation = RELATION_STARTING_POSITION; /* ICC needs this */
break;
case H_GOT_UNWANTED_HEADER:
/* This is an initial board that we don't want */
return;
case H_GETTING_MOVES:
/* Should not happen */
DisplayError(_("Error gathering move list: extra board"), 0);
ics_getting_history = H_FALSE;
return;
}
if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
move_str[1] == '@' && !gameInfo.holdingsWidth ||
weird && (int)gameInfo.variant < (int)VariantShogi) {
/* [HGM] We seem to have switched variant unexpectedly
* Try to guess new variant from board size
*/
VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
if(ranks == 8 && files == 12) newVariant = VariantCourier; else
if(ranks == 9 && files == 9) newVariant = VariantShogi; else
if(ranks == 10 && files == 10) newVariant = VariantGrand; else
if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
VariantSwitch(boards[currentMove], newVariant); /* temp guess */
/* Get a move list just to see the header, which
will tell us whether this is really bug or zh */
if (ics_getting_history == H_FALSE) {
ics_getting_history = H_REQUESTED; reqFlag = TRUE;
snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
SendToICS(str);
}
}
/* Take action if this is the first board of a new game, or of a
different game than is currently being displayed. */
if (gamenum != ics_gamenum || newGameMode != gameMode ||
relation == RELATION_ISOLATED_BOARD) {
/* Forget the old game and get the history (if any) of the new one */
if (gameMode != BeginningOfGame) {
Reset(TRUE, TRUE);
}
newGame = TRUE;
if (appData.autoRaiseBoard) BoardToTop();
prevMove = -3;
if (gamenum == -1) {
newGameMode = IcsIdle;
} else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
appData.getMoveList && !reqFlag) {
/* Need to get game history */
ics_getting_history = H_REQUESTED;
snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
SendToICS(str);
}
/* Initially flip the board to have black on the bottom if playing
black or if the ICS flip flag is set, but let the user change
it with the Flip View button. */
flipView = appData.autoFlipView ?
(newGameMode == IcsPlayingBlack) || ics_flip :
appData.flipView;
/* Done with values from previous mode; copy in new ones */
gameMode = newGameMode;
ModeHighlight();
ics_gamenum = gamenum;
if (gamenum == gs_gamenum) {
int klen = strlen(gs_kind);
if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
gameInfo.event = StrSave(str);
} else {
gameInfo.event = StrSave("ICS game");
}
gameInfo.site = StrSave(appData.icsHost);
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave(white);
gameInfo.black = StrSave(black);
timeControl = basetime * 60 * 1000;
timeControl_2 = 0;
timeIncrement = increment * 1000;
movesPerSession = 0;
gameInfo.timeControl = TimeControlTagValue();
VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
if (appData.debugMode) {
fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
setbuf(debugFP, NULL);
}
gameInfo.outOfBook = NULL;
/* Do we have the ratings? */
if (strcmp(player1Name, white) == 0 &&
strcmp(player2Name, black) == 0) {
if (appData.debugMode)
fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
player1Rating, player2Rating);
gameInfo.whiteRating = player1Rating;
gameInfo.blackRating = player2Rating;
} else if (strcmp(player2Name, white) == 0 &&
strcmp(player1Name, black) == 0) {
if (appData.debugMode)
fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
player2Rating, player1Rating);
gameInfo.whiteRating = player2Rating;
gameInfo.blackRating = player1Rating;
}
player1Name[0] = player2Name[0] = NULLCHAR;
/* Silence shouts if requested */
if (appData.quietPlay &&
(gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
SendToICS(ics_prefix);
SendToICS("set shout 0\n");
}
}
/* Deal with midgame name changes */
if (!newGame) {
if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
if (gameInfo.white) free(gameInfo.white);
gameInfo.white = StrSave(white);
}
if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
if (gameInfo.black) free(gameInfo.black);
gameInfo.black = StrSave(black);
}
}
/* Throw away game result if anything actually changes in examine mode */
if (gameMode == IcsExamining && !newGame) {
gameInfo.result = GameUnfinished;
if (gameInfo.resultDetails != NULL) {
free(gameInfo.resultDetails);
gameInfo.resultDetails = NULL;
}
}
/* In pausing && IcsExamining mode, we ignore boards coming
in if they are in a different variation than we are. */
if (pauseExamInvalid) return;
if (pausing && gameMode == IcsExamining) {
if (moveNum <= pauseExamForwardMostMove) {
pauseExamInvalid = TRUE;
forwardMostMove = pauseExamForwardMostMove;
return;
}
}
if (appData.debugMode) {
fprintf(debugFP, "load %dx%d board\n", files, ranks);
}
/* Parse the board */
for (k = 0; k < ranks; k++) {
for (j = 0; j < files; j++)
board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
if(gameInfo.holdingsWidth > 1) {
board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
}
}
if(moveNum==0 && gameInfo.variant == VariantSChess) {
board[5][BOARD_RGHT+1] = WhiteAngel;
board[6][BOARD_RGHT+1] = WhiteMarshall;
board[1][0] = BlackMarshall;
board[2][0] = BlackAngel;
board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
}
CopyBoard(boards[moveNum], board);
boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
if (moveNum == 0) {
startedFromSetupPosition =
!CompareBoards(board, initialPosition);
if(startedFromSetupPosition)
initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
}
/* [HGM] Set castling rights. Take the outermost Rooks,
to make it also work for FRC opening positions. Note that board12
is really defective for later FRC positions, as it has no way to
indicate which Rook can castle if they are on the same side of King.
For the initial position we grant rights to the outermost Rooks,
and remember thos rights, and we then copy them on positions
later in an FRC game. This means WB might not recognize castlings with
Rooks that have moved back to their original position as illegal,
but in ICS mode that is not its job anyway.
*/
if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
{ int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
if(board[0][i] == WhiteRook) j = i;
initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
if(board[0][i] == WhiteRook) j = i;
initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
if(board[BOARD_HEIGHT-1][k] == bKing)
initialRights[5] = boards[moveNum][CASTLING][5] = k;
if(gameInfo.variant == VariantTwoKings) {
// In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
}
} else { int r;
r = boards[moveNum][CASTLING][0] = initialRights[0];
if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
r = boards[moveNum][CASTLING][1] = initialRights[1];
if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
r = boards[moveNum][CASTLING][3] = initialRights[3];
if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
r = boards[moveNum][CASTLING][4] = initialRights[4];
if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
/* wildcastle kludge: always assume King has rights */
r = boards[moveNum][CASTLING][2] = initialRights[2];
r = boards[moveNum][CASTLING][5] = initialRights[5];
}
/* [HGM] e.p. rights. Assume that ICS sends file number here? */
boards[moveNum][EP_STATUS] = EP_NONE;
if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
if (ics_getting_history == H_GOT_REQ_HEADER ||
ics_getting_history == H_GOT_UNREQ_HEADER) {
/* This was an initial position from a move list, not
the current position */
return;
}
/* Update currentMove and known move number limits */
newMove = newGame || moveNum > forwardMostMove;
if (newGame) {
forwardMostMove = backwardMostMove = currentMove = moveNum;
if (gameMode == IcsExamining && moveNum == 0) {
/* Workaround for ICS limitation: we are not told the wild
type when starting to examine a game. But if we ask for
the move list, the move list header will tell us */
ics_getting_history = H_REQUESTED;
snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
SendToICS(str);
}
} else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
|| (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
#if ZIPPY
/* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
/* [HGM] applied this also to an engine that is silently watching */
if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
(gameMode == IcsObserving || gameMode == IcsExamining) &&
gameInfo.variant == currentlyInitializedVariant) {
takeback = forwardMostMove - moveNum;
for (i = 0; i < takeback; i++) {
if (appData.debugMode) fprintf(debugFP, "take back move\n");
SendToProgram("undo\n", &first);
}
}
#endif
forwardMostMove = moveNum;
if (!pausing || currentMove > forwardMostMove)
currentMove = forwardMostMove;
} else {
/* New part of history that is not contiguous with old part */
if (pausing && gameMode == IcsExamining) {
pauseExamInvalid = TRUE;
forwardMostMove = pauseExamForwardMostMove;
return;
}
if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
#if ZIPPY
if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
// [HGM] when we will receive the move list we now request, it will be
// fed to the engine from the first move on. So if the engine is not
// in the initial position now, bring it there.
InitChessProgram(&first, 0);
}
#endif
ics_getting_history = H_REQUESTED;
snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
SendToICS(str);
}
forwardMostMove = backwardMostMove = currentMove = moveNum;
}
/* Update the clocks */
if (strchr(elapsed_time, '.')) {
/* Time is in ms */
timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
} else {
/* Time is in seconds */
timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
}
#if ZIPPY
if (appData.zippyPlay && newGame &&
gameMode != IcsObserving && gameMode != IcsIdle &&
gameMode != IcsExamining)
ZippyFirstBoard(moveNum, basetime, increment);
#endif
/* Put the move on the move list, first converting
to canonical algebraic form. */
if (moveNum > 0) {
if (appData.debugMode) {
int f = forwardMostMove;
fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
fprintf(debugFP, "moveNum = %d\n", moveNum);
fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
setbuf(debugFP, NULL);
}
if (moveNum <= backwardMostMove) {
/* We don't know what the board looked like before
this move. Punt. */
safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
strcat(parseList[moveNum - 1], " ");
strcat(parseList[moveNum - 1], elapsed_time);
moveList[moveNum - 1][0] = NULLCHAR;
} else if (strcmp(move_str, "none") == 0) {
// [HGM] long SAN: swapped order; test for 'none' before parsing move
/* Again, we don't know what the board looked like;
this is really the start of the game. */
parseList[moveNum - 1][0] = NULLCHAR;
moveList[moveNum - 1][0] = NULLCHAR;
backwardMostMove = moveNum;
startedFromSetupPosition = TRUE;
fromX = fromY = toX = toY = -1;
} else {
// [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
// So we parse the long-algebraic move string in stead of the SAN move
int valid; char buf[MSG_SIZ], *prom;
if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
// str looks something like "Q/a1-a2"; kill the slash
if(str[1] == '/')
snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
strcat(buf, prom); // long move lacks promo specification!
if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
if(appData.debugMode)
fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
safeStrCpy(move_str, buf, MSG_SIZ);
}
valid = ParseOneMove(move_str, moveNum - 1, &moveType,
&fromX, &fromY, &toX, &toY, &promoChar)
|| ParseOneMove(buf, moveNum - 1, &moveType,
&fromX, &fromY, &toX, &toY, &promoChar);
// end of long SAN patch
if (valid) {
(void) CoordsToAlgebraic(boards[moveNum - 1],
PosFlags(moveNum - 1),
fromY, fromX, toY, toX, promoChar,
parseList[moveNum-1]);
switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
case MT_NONE:
case MT_STALEMATE:
default:
break;
case MT_CHECK:
if(!IS_SHOGI(gameInfo.variant))
strcat(parseList[moveNum - 1], "+");
break;
case MT_CHECKMATE:
case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
strcat(parseList[moveNum - 1], "#");
break;
}
strcat(parseList[moveNum - 1], " ");
strcat(parseList[moveNum - 1], elapsed_time);
/* currentMoveString is set as a side-effect of ParseOneMove */
if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
strcat(moveList[moveNum - 1], "\n");
if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
&& gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
ChessSquare old, new = boards[moveNum][k][j];
if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
if(old == new) continue;
if(old == PROMOTED(new)) boards[moveNum][k][j] = old;// prevent promoted pieces to revert to primordial ones
else if(new == WhiteWazir || new == BlackWazir) {
if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
boards[moveNum][k][j] = PROMOTED(old); // choose correct type of Gold in promotion
else boards[moveNum][k][j] = old; // preserve type of Gold
} else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
boards[moveNum][k][j] = PROMOTED(new); // use non-primordial representation of chosen piece
}
} else {
/* Move from ICS was illegal!? Punt. */
if (appData.debugMode) {
fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
}
safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
strcat(parseList[moveNum - 1], " ");
strcat(parseList[moveNum - 1], elapsed_time);
moveList[moveNum - 1][0] = NULLCHAR;
fromX = fromY = toX = toY = -1;
}
}
if (appData.debugMode) {
fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
setbuf(debugFP, NULL);
}
#if ZIPPY
/* Send move to chess program (BEFORE animating it). */
if (appData.zippyPlay && !newGame && newMove &&
(!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
(gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
if (moveList[moveNum - 1][0] == NULLCHAR) {
snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
move_str);
DisplayError(str, 0);
} else {
if (first.sendTime) {
SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
}
bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
if (firstMove && !bookHit) {
firstMove = FALSE;
if (first.useColors) {
SendToProgram(gameMode == IcsPlayingWhite ?
"white\ngo\n" :
"black\ngo\n", &first);
} else {
SendToProgram("go\n", &first);
}
first.maybeThinking = TRUE;
}
}
} else if (gameMode == IcsObserving || gameMode == IcsExamining) {
if (moveList[moveNum - 1][0] == NULLCHAR) {
snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
DisplayError(str, 0);
} else {
if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
SendMoveToProgram(moveNum - 1, &first);
}
}
}
#endif
}
if (moveNum > 0 && !gotPremove && !appData.noGUI) {
/* If move comes from a remote source, animate it. If it
isn't remote, it will have already been animated. */
if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
}
if (!pausing && appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
}
}
/* Start the clocks */
whiteFlag = blackFlag = FALSE;
appData.clockMode = !(basetime == 0 && increment == 0);
if (ticking == 0) {
ics_clock_paused = TRUE;
StopClocks();
} else if (ticking == 1) {
ics_clock_paused = FALSE;
}
if (gameMode == IcsIdle ||
relation == RELATION_OBSERVING_STATIC ||
relation == RELATION_EXAMINING ||
ics_clock_paused)
DisplayBothClocks();
else
StartClocks();
/* Display opponents and material strengths */
if (gameInfo.variant != VariantBughouse &&
gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
if (tinyLayout || smallLayout) {
if(gameInfo.variant == VariantNormal)
snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
gameInfo.white, white_stren, gameInfo.black, black_stren,
basetime, increment);
else
snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
gameInfo.white, white_stren, gameInfo.black, black_stren,
basetime, increment, (int) gameInfo.variant);
} else {
if(gameInfo.variant == VariantNormal)
snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
basetime, increment);
else
snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
basetime, increment, VariantName(gameInfo.variant));
}
DisplayTitle(str);
if (appData.debugMode) {
fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
}
}
/* Display the board */
if (!pausing && !appData.noGUI) {
if (appData.premove)
if (!gotPremove ||
((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
ClearPremoveHighlights();
j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
DrawPosition(j, boards[currentMove]);
DisplayMove(moveNum - 1);
if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
!((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
(gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
if(newMove) RingBell(); else PlayIcsUnfinishedSound();
}
}
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
#if ZIPPY
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
HandleMachineMove(bookMove, &first);
}
#endif
}
void
GetMoveListEvent ()
{
char buf[MSG_SIZ];
if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
ics_getting_history = H_REQUESTED;
snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
SendToICS(buf);
}
}
void
SendToBoth (char *msg)
{ // to make it easy to keep two engines in step in dual analysis
SendToProgram(msg, &first);
if(second.analyzing) SendToProgram(msg, &second);
}
void
AnalysisPeriodicEvent (int force)
{
if (((programStats.ok_to_send == 0 || programStats.line_is_book)
&& !force) || !appData.periodicUpdates)
return;
/* Send . command to Crafty to collect stats */
SendToBoth(".\n");
/* Don't send another until we get a response (this makes
us stop sending to old Crafty's which don't understand
the "." command (sending illegal cmds resets node count & time,
which looks bad)) */
programStats.ok_to_send = 0;
}
void
ics_update_width (int new_width)
{
ics_printf("set width %d\n", new_width);
}
void
SendMoveToProgram (int moveNum, ChessProgramState *cps)
{
char buf[MSG_SIZ];
if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
if(gameInfo.variant == VariantLion || gameInfo.variant == VariantChuChess || gameInfo.variant == VariantChu) {
sprintf(buf, "%s@@@@\n", cps->useUsermove ? "usermove " : "");
SendToProgram(buf, cps);
return;
}
// null move in variant where engine does not understand it (for analysis purposes)
SendBoard(cps, moveNum + 1); // send position after move in stead.
return;
}
if (cps->useUsermove) {
SendToProgram("usermove ", cps);
}
if (cps->useSAN) {
char *space;
if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
int len = space - parseList[moveNum];
memcpy(buf, parseList[moveNum], len);
buf[len++] = '\n';
buf[len] = NULLCHAR;
} else {
snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
}
SendToProgram(buf, cps);
} else {
if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
AlphaRank(moveList[moveNum], 4);
SendToProgram(moveList[moveNum], cps);
AlphaRank(moveList[moveNum], 4); // and back
} else
/* Added by Tord: Send castle moves in "O-O" in FRC games if required by
* the engine. It would be nice to have a better way to identify castle
* moves here. */
if(appData.fischerCastling && cps->useOOCastle) {
int fromX = moveList[moveNum][0] - AAA;
int fromY = moveList[moveNum][1] - ONE;
int toX = moveList[moveNum][2] - AAA;
int toY = moveList[moveNum][3] - ONE;
if((boards[moveNum][fromY][fromX] == WhiteKing
&& boards[moveNum][toY][toX] == WhiteRook)
|| (boards[moveNum][fromY][fromX] == BlackKing
&& boards[moveNum][toY][toX] == BlackRook)) {
if(toX > fromX) SendToProgram("O-O\n", cps);
else SendToProgram("O-O-O\n", cps);
}
else SendToProgram(moveList[moveNum], cps);
} else
if(moveList[moveNum][4] == ';') { // [HGM] lion: move is double-step over intermediate square
char *m = moveList[moveNum];
static char c[2];
*c = m[7]; if(*c == '\n') *c = NULLCHAR; // promoChar
if((boards[moveNum][m[6]-ONE][m[5]-AAA] < BlackPawn) == (boards[moveNum][m[1]-ONE][m[0]-AAA] < BlackPawn)) // move is kludge to indicate castling
snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d\n", m[0], m[1] - '0', // convert to two moves
m[2], m[3] - '0',
m[5], m[6] - '0',
m[2] + (m[0] > m[5] ? 1 : -1), m[3] - '0');
else if(*c && m[8] != '\n') { // kill square followed by 2 characters: 2nd kill square rather than promo suffix
*c = m[9]; if(*c == '\n') *c = NULLCHAR;
snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to three moves
m[7], m[8] - '0',
m[7], m[8] - '0',
m[5], m[6] - '0',
m[5], m[6] - '0',
m[2], m[3] - '0', c);
} else
snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to two moves
m[5], m[6] - '0',
m[5], m[6] - '0',
m[2], m[3] - '0', c);
SendToProgram(buf, cps);
} else
if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
} else
snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
SendToProgram(buf, cps);
}
else SendToProgram(moveList[moveNum], cps);
/* End of additions by Tord */
}
/* [HGM] setting up the opening has brought engine in force mode! */
/* Send 'go' if we are in a mode where machine should play. */
if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
(gameMode == TwoMachinesPlay ||
#if ZIPPY
gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
#endif
gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
SendToProgram("go\n", cps);
if (appData.debugMode) {
fprintf(debugFP, "(extra)\n");
}
}
setboardSpoiledMachineBlack = 0;
}
void
SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
{
char user_move[MSG_SIZ];
char suffix[4];
if(gameInfo.variant == VariantSChess && promoChar) {
snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
} else suffix[0] = NULLCHAR;
switch (moveType) {
default:
snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
(int)moveType, fromX, fromY, toX, toY);
DisplayError(user_move + strlen("say "), 0);
break;
case WhiteKingSideCastle:
case BlackKingSideCastle:
case WhiteQueenSideCastleWild:
case BlackQueenSideCastleWild:
/* PUSH Fabien */
case WhiteHSideCastleFR:
case BlackHSideCastleFR:
/* POP Fabien */
snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
break;
case WhiteQueenSideCastle:
case BlackQueenSideCastle:
case WhiteKingSideCastleWild:
case BlackKingSideCastleWild:
/* PUSH Fabien */
case WhiteASideCastleFR:
case BlackASideCastleFR:
/* POP Fabien */
snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
break;
case WhiteNonPromotion:
case BlackNonPromotion:
sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
break;
case WhitePromotion:
case BlackPromotion:
if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
gameInfo.variant == VariantMakruk)
snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
PieceToChar(WhiteFerz));
else if(gameInfo.variant == VariantGreat)
snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
PieceToChar(WhiteMan));
else
snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
promoChar);
break;
case WhiteDrop:
case BlackDrop:
drop:
snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
ToUpper(PieceToChar((ChessSquare) fromX)),
AAA + toX, ONE + toY);
break;
case IllegalMove: /* could be a variant we don't quite understand */
if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
case NormalMove:
case WhiteCapturesEnPassant:
case BlackCapturesEnPassant:
snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
break;
}
SendToICS(user_move);
if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
}
void
UploadGameEvent ()
{ // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
DisplayError(_("You cannot do this while you are playing or observing"), 0);
return;
}
if(gameMode != IcsExamining) { // is this ever not the case?
char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
snprintf(command,MSG_SIZ, "match %s", ics_handle);
} else { // on FICS we must first go to general examine mode
safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
}
if(gameInfo.variant != VariantNormal) {
// try figure out wild number, as xboard names are not always valid on ICS
for(i=1; i<=36; i++) {
snprintf(buf, MSG_SIZ, "wild/%d", i);
if(StringToVariant(buf) == gameInfo.variant) break;
}
if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
} else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
SendToICS(ics_prefix);
SendToICS(buf);
if(startedFromSetupPosition || backwardMostMove != 0) {
fen = PositionToFEN(backwardMostMove, NULL, 1);
if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
SendToICS(buf);
} else { // FICS: everything has to set by separate bsetup commands
p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
SendToICS(buf);
if(!WhiteOnMove(backwardMostMove)) {
SendToICS("bsetup tomove black\n");
}
i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
SendToICS(buf);
i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
SendToICS(buf);
i = boards[backwardMostMove][EP_STATUS];
if(i >= 0) { // set e.p.
snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
SendToICS(buf);
}
bsetup++;
}
}
if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
SendToICS("bsetup done\n"); // switch to normal examining.
}
for(i = backwardMostMove; i<last; i++) {
char buf[20];
snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
int len = strlen(moveList[i]);
snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
}
SendToICS(buf);
}
SendToICS(ics_prefix);
SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
}
int killX = -1, killY = -1, kill2X = -1, kill2Y = -1; // [HGM] lion: used for passing e.p. capture square to MakeMove
int legNr = 1;
void
CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[9])
{
if (rf == DROP_RANK) {
if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
sprintf(move, "%c@%c%c\n",
ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
} else {
if (promoChar == 'x' || promoChar == NULLCHAR) {
sprintf(move, "%c%c%c%c\n",
AAA + ff, ONE + rf, AAA + ft, ONE + rt);
if(killX >= 0 && killY >= 0) {
sprintf(move+4, ";%c%c\n", AAA + killX, ONE + killY);
if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c\n", AAA + kill2X, ONE + kill2Y);
}
} else {
sprintf(move, "%c%c%c%c%c\n",
AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
if(killX >= 0 && killY >= 0) {
sprintf(move+4, ";%c%c%c\n", AAA + killX, ONE + killY, promoChar);
if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c%c\n", AAA + kill2X, ONE + kill2Y, promoChar);
}
}
}
}
void
ProcessICSInitScript (FILE *f)
{
char buf[MSG_SIZ];
while (fgets(buf, MSG_SIZ, f)) {
SendToICSDelayed(buf,(long)appData.msLoginDelay);
}
fclose(f);
}
static int lastX, lastY, lastLeftX, lastLeftY, selectFlag;
int dragging;
static ClickType lastClickType;
int
PieceInString (char *s, ChessSquare piece)
{
char *p, ID = ToUpper(PieceToChar(piece)), suffix = PieceSuffix(piece);
while((p = strchr(s, ID))) {
if(!suffix || p[1] == suffix) return TRUE;
s = p;
}
return FALSE;
}
int
Partner (ChessSquare *p)
{ // change piece into promotion partner if one shogi-promotes to the other
ChessSquare partner = promoPartner[*p];
if(PieceToChar(*p) != '+' && PieceToChar(partner) != '+') return 0;
if(PieceToChar(*p) == '+') partner = boards[currentMove][fromY][fromX];
*p = partner;
return 1;
}
void
Sweep (int step)
{
ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
static int toggleFlag;
if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
if(fromY != BOARD_HEIGHT-2 && fromY != 1 && gameInfo.variant != VariantChuChess) pawn = EmptySquare;
if(!step) toggleFlag = Partner(&last); // piece has shogi-promotion
do {
if(step && !(toggleFlag && Partner(&promoSweep))) promoSweep -= step;
if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
else if((int)promoSweep == -1) promoSweep = WhiteKing;
else if(promoSweep == BlackPawn && step < 0 && !toggleFlag) promoSweep = WhitePawn;
else if(promoSweep == WhiteKing && step > 0 && !toggleFlag) promoSweep = BlackKing;
if(!step) step = -1;
} while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' ||
!toggleFlag && PieceToChar(promoSweep) == '+' || // skip promoted versions of other
promoRestrict[0] ? !PieceInString(promoRestrict, promoSweep) : // if choice set available, use it
promoSweep == pawn ||
appData.testLegality && (promoSweep == king || gameInfo.variant != VariantChuChess &&
(promoSweep == WhiteLion || promoSweep == BlackLion)));
if(toX >= 0) {
int victim = boards[currentMove][toY][toX];
boards[currentMove][toY][toX] = promoSweep;
DrawPosition(FALSE, boards[currentMove]);
boards[currentMove][toY][toX] = victim;
} else
ChangeDragPiece(promoSweep);
}
int
PromoScroll (int x, int y)
{
int step = 0;
if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
if(!step) return FALSE;
lastX = x; lastY = y;
if((promoSweep < BlackPawn) == flipView) step = -step;
if(step > 0) selectFlag = 1;
if(!selectFlag) Sweep(step);
return FALSE;
}
void
NextPiece (int step)
{
ChessSquare piece = boards[currentMove][toY][toX];
do {
pieceSweep -= step;
if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
if((int)pieceSweep == -1) pieceSweep = BlackKing;
if(!step) step = -1;
} while(PieceToChar(pieceSweep) == '.');
boards[currentMove][toY][toX] = pieceSweep;
DrawPosition(FALSE, boards[currentMove]);
boards[currentMove][toY][toX] = piece;
}
/* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
void
AlphaRank (char *move, int n)
{
// char *p = move, c; int x, y;
if (appData.debugMode) {
fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
}
if(move[1]=='*' &&
move[2]>='0' && move[2]<='9' &&
move[3]>='a' && move[3]<='x' ) {
move[1] = '@';
move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
} else
if(move[0]>='0' && move[0]<='9' &&
move[1]>='a' && move[1]<='x' &&
move[2]>='0' && move[2]<='9' &&
move[3]>='a' && move[3]<='x' ) {
/* input move, Shogi -> normal */
move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
} else
if(move[1]=='@' &&
move[3]>='0' && move[3]<='9' &&
move[2]>='a' && move[2]<='x' ) {
move[1] = '*';
move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
} else
if(
move[0]>='a' && move[0]<='x' &&
move[3]>='0' && move[3]<='9' &&
move[2]>='a' && move[2]<='x' ) {
/* output move, normal -> Shogi */
move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
}
if (appData.debugMode) {
fprintf(debugFP, " out = '%s'\n", move);
}
}
char yy_textstr[8000];
/* Parser for moves from gnuchess, ICS, or user typein box */
Boolean
ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
{
*moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
switch (*moveType) {
case WhitePromotion:
case BlackPromotion:
case WhiteNonPromotion:
case BlackNonPromotion:
case NormalMove:
case FirstLeg:
case WhiteCapturesEnPassant:
case BlackCapturesEnPassant:
case WhiteKingSideCastle:
case WhiteQueenSideCastle:
case BlackKingSideCastle:
case BlackQueenSideCastle:
case WhiteKingSideCastleWild:
case WhiteQueenSideCastleWild:
case BlackKingSideCastleWild:
case BlackQueenSideCastleWild:
/* Code added by Tord: */
case WhiteHSideCastleFR:
case WhiteASideCastleFR:
case BlackHSideCastleFR:
case BlackASideCastleFR:
/* End of code added by Tord */
case IllegalMove: /* bug or odd chess variant */
if(currentMoveString[1] == '@') { // illegal drop
*fromX = WhiteOnMove(moveNum) ?
(int) CharToPiece(ToUpper(currentMoveString[0])) :
(int) CharToPiece(ToLower(currentMoveString[0]));
goto drop;
}
*fromX = currentMoveString[0] - AAA;
*fromY = currentMoveString[1] - ONE;
*toX = currentMoveString[2] - AAA;
*toY = currentMoveString[3] - ONE;
*promoChar = currentMoveString[4];
if(*promoChar == ';') *promoChar = currentMoveString[7 + 2*(currentMoveString[8] != 0)];
if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
*toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
if (appData.debugMode) {
fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
}
*fromX = *fromY = *toX = *toY = 0;
return FALSE;
}
if (appData.testLegality) {
return (*moveType != IllegalMove);
} else {
return !(*fromX == *toX && *fromY == *toY && killX < 0) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
// [HGM] lion: if this is a double move we are less critical
WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
}
case WhiteDrop:
case BlackDrop:
*fromX = *moveType == WhiteDrop ?
(int) CharToPiece(ToUpper(currentMoveString[0])) :
(int) CharToPiece(ToLower(currentMoveString[0]));
drop:
*fromY = DROP_RANK;
*toX = currentMoveString[2] - AAA;
*toY = currentMoveString[3] - ONE;
*promoChar = NULLCHAR;
return TRUE;
case AmbiguousMove:
case ImpossibleMove:
case EndOfFile:
case ElapsedTime:
case Comment:
case PGNTag:
case NAG:
case WhiteWins:
case BlackWins:
case GameIsDrawn:
default:
if (appData.debugMode) {
fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
}
/* bug? */
*fromX = *fromY = *toX = *toY = 0;
*promoChar = NULLCHAR;
return FALSE;
}
}
Boolean pushed = FALSE;
char *lastParseAttempt;
void
ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
{ // Parse a string of PV moves, and append to current game, behind forwardMostMove
int fromX, fromY, toX, toY; char promoChar;
ChessMove moveType;
Boolean valid;
int nr = 0;
lastParseAttempt = pv; if(!*pv) return; // turns out we crash when we parse an empty PV
if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
pushed = TRUE;
}
endPV = forwardMostMove;
do {
while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
lastParseAttempt = pv;
valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
if(!valid && nr == 0 &&
ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
// Hande case where played move is different from leading PV move
CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
if(!CompareBoards(boards[endPV], boards[endPV+2])) {
endPV += 2; // if position different, keep this
moveList[endPV-1][0] = fromX + AAA;
moveList[endPV-1][1] = fromY + ONE;
moveList[endPV-1][2] = toX + AAA;
moveList[endPV-1][3] = toY + ONE;
parseList[endPV-1][0] = NULLCHAR;
safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
}
}
pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
valid++; // allow comments in PV
continue;
}
nr++;
if(endPV+1 > framePtr) break; // no space, truncate
if(!valid) break;
endPV++;
CopyBoard(boards[endPV], boards[endPV-1]);
ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
strncat(moveList[endPV-1], "\n", MOVE_LEN);
CoordsToAlgebraic(boards[endPV - 1],
PosFlags(endPV - 1),
fromY, fromX, toY, toX, promoChar,
parseList[endPV - 1]);
} while(valid);
if(atEnd == 2) return; // used hidden, for PV conversion
currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
DrawPosition(TRUE, boards[currentMove]);
}
int
MultiPV (ChessProgramState *cps, int kind)
{ // check if engine supports MultiPV, and if so, return the number of the option that sets it
int i;
for(i=0; i<cps->nrOptions; i++) {
char *s = cps->option[i].name;
if((kind & 1) && !StrCaseCmp(s, "MultiPV") && cps->option[i].type == Spin) return i;
if((kind & 2) && StrCaseStr(s, "multi") && StrCaseStr(s, "PV")
&& StrCaseStr(s, "margin") && cps->option[i].type == Spin) return -i-2;
}
return -1;
}
Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
static int multi, pv_margin;
static ChessProgramState *activeCps;
Boolean
LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
{
int startPV, lineStart, origIndex = index;
char *p, buf2[MSG_SIZ];
ChessProgramState *cps = (pane ? &second : &first);
if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
lastX = x; lastY = y;
while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
lineStart = startPV = index;
while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
index = startPV;
do{ while(buf[index] && buf[index] != '\n') index++;
} while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
buf[index] = 0;
if(lineStart == 0 && gameMode == AnalyzeMode) {
int n = 0;
if(origIndex > 17 && origIndex < 24) n--; else if(origIndex > index - 6) n++;
if(n == 0) { // click not on "fewer" or "more"
if((multi = -2 - MultiPV(cps, 2)) >= 0) {
pv_margin = cps->option[multi].value;
activeCps = cps; // non-null signals margin adjustment
}
} else if((multi = MultiPV(cps, 1)) >= 0) {
n += cps->option[multi].value; if(n < 1) n = 1;
snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
if(cps->option[multi].value != n) SendToProgram(buf2, cps);
cps->option[multi].value = n;
*start = *end = 0;
return FALSE;
}
} else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
ExcludeClick(origIndex - lineStart);
return FALSE;
} else if(!strncmp(buf+lineStart, "dep\t", 4)) { // column headers clicked
Collapse(origIndex - lineStart);
return FALSE;
}
ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
*start = startPV; *end = index-1;
extendGame = (gameMode == AnalyzeMode && appData.autoExtend && origIndex - startPV < 5);
return TRUE;
}
char *
PvToSAN (char *pv)
{
static char buf[10*MSG_SIZ];
int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
*buf = NULLCHAR;
if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
for(i = forwardMostMove; i<endPV; i++){
if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
k += strlen(buf+k);
}
snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
endPV = savedEnd;
return buf;
}
Boolean
LoadPV (int x, int y)
{ // called on right mouse click to load PV
int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
lastX = x; lastY = y;
ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
extendGame = FALSE;
return TRUE;
}
void
UnLoadPV ()
{
int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
if(activeCps) {
if(pv_margin != activeCps->option[multi].value) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "option %s=%d\n", "Multi-PV Margin", pv_margin);
SendToProgram(buf, activeCps);
activeCps->option[multi].value = pv_margin;
}
activeCps = NULL;
return;
}
if(endPV < 0) return;
if(appData.autoCopyPV) CopyFENToClipboard();
endPV = -1;
if(extendGame && currentMove > forwardMostMove) {
Boolean saveAnimate = appData.animate;
if(pushed) {
if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
} else storedGames--; // abandon shelved tail of original game
}
pushed = FALSE;
forwardMostMove = currentMove;
currentMove = oldFMM;
appData.animate = FALSE;
ToNrEvent(forwardMostMove);
appData.animate = saveAnimate;
}
currentMove = forwardMostMove;
if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
ClearPremoveHighlights();
DrawPosition(TRUE, boards[currentMove]);
}
void
MovePV (int x, int y, int h)
{ // step through PV based on mouse coordinates (called on mouse move)
int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
if(activeCps) { // adjusting engine's multi-pv margin
if(x > lastX) pv_margin++; else
if(x < lastX) pv_margin -= (pv_margin > 0);
if(x != lastX) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "margin = %d", pv_margin);
DisplayMessage(buf, "");
}
lastX = x;
return;
}
// we must somehow check if right button is still down (might be released off board!)
if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
if(!step) return;
lastX = x; lastY = y;
if(pieceSweep != EmptySquare) { NextPiece(step); return; }
if(endPV < 0) return;
if(y < margin) step = 1; else
if(y > h - margin) step = -1;
if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
currentMove += step;
if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
DrawPosition(FALSE, boards[currentMove]);
}
// [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
// All positions will have equal probability, but the current method will not provide a unique
// numbering scheme for arrays that contain 3 or more pieces of the same kind.
#define DARK 1
#define LITE 2
#define ANY 3
int squaresLeft[4];
int piecesLeft[(int)BlackPawn];
int seed, nrOfShuffles;
void
GetPositionNumber ()
{ // sets global variable seed
int i;
seed = appData.defaultFrcPosition;
if(seed < 0) { // randomize based on time for negative FRC position numbers
for(i=0; i<50; i++) seed += random();
seed = random() ^ random() >> 8 ^ random() << 8;
if(seed<0) seed = -seed;
}
}
int
put (Board board, int pieceType, int rank, int n, int shade)
// put the piece on the (n-1)-th empty squares of the given shade
{
int i;
for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
board[rank][i] = (ChessSquare) pieceType;
squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
squaresLeft[ANY]--;
piecesLeft[pieceType]--;
return i;
}
}
return -1;
}
void
AddOnePiece (Board board, int pieceType, int rank, int shade)
// calculate where the next piece goes, (any empty square), and put it there
{
int i;
i = seed % squaresLeft[shade];
nrOfShuffles *= squaresLeft[shade];
seed /= squaresLeft[shade];
put(board, pieceType, rank, i, shade);
}
void
AddTwoPieces (Board board, int pieceType, int rank)
// calculate where the next 2 identical pieces go, (any empty square), and put it there
{
int i, n=squaresLeft[ANY], j=n-1, k;
k = n*(n-1)/2; // nr of possibilities, not counting permutations
i = seed % k; // pick one
nrOfShuffles *= k;
seed /= k;
while(i >= j) i -= j--;
j = n - 1 - j; i += j;
put(board, pieceType, rank, j, ANY);
put(board, pieceType, rank, i, ANY);
}
void
SetUpShuffle (Board board, int number)
{
int i, p, first=1;
GetPositionNumber(); nrOfShuffles = 1;
squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
p = (int) board[0][i];
if(p < (int) BlackPawn) piecesLeft[p] ++;
board[0][i] = EmptySquare;
}
if(PosFlags(0) & F_ALL_CASTLE_OK) {
// shuffles restricted to allow normal castling put KRR first
if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
put(board, WhiteRook, 0, 0, ANY);
// in variants with super-numerary Kings and Rooks, we leave these for the shuffle
}
if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
// only for even boards make effort to put pairs of colorbound pieces on opposite colors
for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
while(piecesLeft[p] >= 2) {
AddOnePiece(board, p, 0, LITE);
AddOnePiece(board, p, 0, DARK);
}
// Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
}
for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
// Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
// but we leave King and Rooks for last, to possibly obey FRC restriction
if(p == (int)WhiteRook) continue;
while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
}
// now everything is placed, except perhaps King (Unicorn) and Rooks
if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
// Last King gets castling rights
while(piecesLeft[(int)WhiteUnicorn]) {
i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
}
while(piecesLeft[(int)WhiteKing]) {
i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
}
} else {
while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
}
// Only Rooks can be left; simply place them all
while(piecesLeft[(int)WhiteRook]) {
i = put(board, WhiteRook, 0, 0, ANY);
if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
if(first) {
first=0;
initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
}
initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
}
}
for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
}
if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
}
int
ptclen (const char *s, char *escapes)
{
int n = 0;
if(!*escapes) return strlen(s);
while(*s) n += (*s != '/' && *s != '-' && *s != '^' && *s != '*' && !strchr(escapes, *s)) - 2*(*s == '='), s++;
return n;
}
int
SetCharTableEsc (unsigned char *table, const char * map, char * escapes)
/* [HGM] moved here from winboard.c because of its general usefulness */
/* Basically a safe strcpy that uses the last character as King */
{
int result = FALSE; int NrPieces;
unsigned char partner[EmptySquare];
if( map != NULL && (NrPieces=ptclen(map, escapes)) <= (int) EmptySquare
&& NrPieces >= 12 && !(NrPieces&1)) {
int i, ii, offs, j = 0; /* [HGM] Accept even length from 12 to 88 */
for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
for( i=offs=0; i<NrPieces/2-1; i++ ) {
char *p, c=0;
if(map[j] == '/') offs = WhitePBishop - i, j++;
if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
table[i+offs] = map[j++];
if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
}
table[(int) WhiteKing] = map[j++];
for( ii=offs=0; ii<NrPieces/2-1; ii++ ) {
char *p, c=0;
if(map[j] == '/') offs = WhitePBishop - ii, j++;
i = WHITE_TO_BLACK ii;
if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
table[i+offs] = map[j++];
if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
}
table[(int) BlackKing] = map[j++];
if(*escapes) { // set up promotion pairing
for( i=0; i<(int) EmptySquare; i++ ) promoPartner[i] = (i%BlackPawn < 11 ? i + 11 : i%BlackPawn < 22 ? i - 11 : i); // default
// pieceToChar entirely filled, so we can look up specified partners
for(i=0; i<EmptySquare; i++) { // adjust promotion pairing
int c = table[i];
if(c == '^' || c == '-') { // has specified partner
int p;
for(p=0; p<EmptySquare; p++) if(table[p] == partner[i]) break;
if(c == '^') table[i] = '+';
if(p < EmptySquare) {
if(promoPartner[promoPartner[p]] == p) promoPartner[promoPartner[p]] = promoPartner[p]; // divorce old partners
if(promoPartner[promoPartner[i]] == i) promoPartner[promoPartner[i]] = promoPartner[i];
promoPartner[p] = i, promoPartner[i] = p; // and marry this couple
}
} else if(c == '*') {
table[i] = partner[i];
promoPartner[i] = (i < BlackPawn ? WhiteTokin : BlackTokin); // promotes to Tokin
}
}
}
result = TRUE;
}
return result;
}
int
SetCharTable (unsigned char *table, const char * map)
{
return SetCharTableEsc(table, map, "");
}
void
Prelude (Board board)
{ // [HGM] superchess: random selection of exo-pieces
int i, j, k; ChessSquare p;
static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
GetPositionNumber(); // use FRC position number
if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
SetCharTable(pieceToChar, appData.pieceToCharTable);
for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
}
j = seed%4; seed /= 4;
p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
j = seed%3 + (seed%3 >= j); seed /= 3;
p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
j = seed%3; seed /= 3;
p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
j = seed%2 + (seed%2 >= j); seed /= 2;
p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
put(board, exoPieces[0], 0, 0, ANY);
for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
}
void
InitPosition (int redraw)
{
ChessSquare (* pieces)[BOARD_FILES];
int i, j, pawnRow=1, pieceRows=1, overrule,
oldx = gameInfo.boardWidth,
oldy = gameInfo.boardHeight,
oldh = gameInfo.holdingsWidth;
static int oldv;
if(appData.icsActive) shuffleOpenings = appData.fischerCastling = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
/* [AS] Initialize pv info list [HGM] and game status */
{
for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
pvInfoList[i].depth = 0;
boards[i][EP_STATUS] = EP_NONE;
for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
}
initialRulePlies = 0; /* 50-move counter start */
castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
}
/* [HGM] logic here is completely changed. In stead of full positions */
/* the initialized data only consist of the two backranks. The switch */
/* selects which one we will use, which is than copied to the Board */
/* initialPosition, which for the rest is initialized by Pawns and */
/* empty squares. This initial position is then copied to boards[0], */
/* possibly after shuffling, so that it remains available. */
gameInfo.holdingsWidth = 0; /* default board sizes */
gameInfo.boardWidth = 8;
gameInfo.boardHeight = 8;
gameInfo.holdingsSize = 0;
nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
for(i=0; i<BOARD_FILES-6; i++)
initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
initialPosition[EP_STATUS] = EP_NONE;
initialPosition[TOUCHED_W] = initialPosition[TOUCHED_B] = 0;
SetCharTableEsc(pieceToChar, "PNBRQ...........Kpnbrq...........k", SUFFIXES);
if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
SetCharTable(pieceNickName, appData.pieceNickNames);
else SetCharTable(pieceNickName, "............");
pieces = FIDEArray;
switch (gameInfo.variant) {
case VariantFischeRandom:
shuffleOpenings = TRUE;
appData.fischerCastling = TRUE;
default:
break;
case VariantShatranj:
pieces = ShatranjArray;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
break;
case VariantMakruk:
pieces = makrukArray;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
break;
case VariantASEAN:
pieces = aseanArray;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PN.R.Q....BKpn.r.q....bk");
break;
case VariantTwoKings:
pieces = twoKingsArray;
break;
case VariantGrand:
pieces = GrandArray;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
gameInfo.boardWidth = 10;
gameInfo.boardHeight = 10;
gameInfo.holdingsSize = 7;
break;
case VariantCapaRandom:
shuffleOpenings = TRUE;
appData.fischerCastling = TRUE;
case VariantCapablanca:
pieces = CapablancaArray;
gameInfo.boardWidth = 10;
SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
break;
case VariantGothic:
pieces = GothicArray;
gameInfo.boardWidth = 10;
SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
break;
case VariantSChess:
SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
gameInfo.holdingsSize = 7;
for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
break;
case VariantJanus:
pieces = JanusArray;
gameInfo.boardWidth = 10;
SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
nrCastlingRights = 6;
initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
break;
case VariantFalcon:
pieces = FalconArray;
gameInfo.boardWidth = 10;
SetCharTable(pieceToChar, "PNBRQ............FKpnbrq............fk");
break;
case VariantXiangqi:
pieces = XiangqiArray;
gameInfo.boardWidth = 9;
gameInfo.boardHeight = 10;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
break;
case VariantShogi:
pieces = ShogiArray;
gameInfo.boardWidth = 9;
gameInfo.boardHeight = 9;
gameInfo.holdingsSize = 7;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
break;
case VariantChu:
pieces = ChuArray; pieceRows = 3;
gameInfo.boardWidth = 12;
gameInfo.boardHeight = 12;
nrCastlingRights = 0;
// SetCharTableEsc(pieceToChar, "P.BRQSEXOGCATHD.VMLIFN.........^T..^L......^A^H/^F^G^M.^E^X^O^I.^P.^B^R..^D^S^C^VK"
// "p.brqsexogcathd.vmlifn.........^t..^l......^a^h/^f^g^m.^e^x^o^i.^p.^b^r..^d^s^c^vk", SUFFIXES);
SetCharTableEsc(pieceToChar, "P.BRQSEXOG...HD..^DLI^HNV........^T..^L.C...A^AFT/^F^G^M.^E^X^O^I.^P.^B^R..M^S^C^VK"
"p.brqsexog...hd..^dli^hnv........^t..^l.c...a^aft/^f^g^m.^e^x^o^i.^p.^b^r..m^s^c^vk", SUFFIXES);
break;
case VariantCourier:
pieces = CourierArray;
gameInfo.boardWidth = 12;
nrCastlingRights = 0;
SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
break;
case VariantKnightmate:
pieces = KnightmateArray;
SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
break;
case VariantSpartan:
pieces = SpartanArray;
SetCharTable(pieceToChar, "PNBRQ.....................K......lw......g...h......ck");
break;
case VariantLion:
pieces = lionArray;
SetCharTable(pieceToChar, "PNBRQ................LKpnbrq................lk");
break;
case VariantChuChess:
pieces = ChuChessArray;
gameInfo.boardWidth = 10;
gameInfo.boardHeight = 10;
SetCharTable(pieceToChar, "PNBRQ.....M.+++......LKpnbrq.....m.+++......lk");
break;
case VariantFairy:
pieces = fairyArray;
SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
break;
case VariantGreat:
pieces = GreatArray;
gameInfo.boardWidth = 10;
SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
gameInfo.holdingsSize = 8;
break;
case VariantSuper:
pieces = FIDEArray;
SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
gameInfo.holdingsSize = 8;
startedFromSetupPosition = TRUE;
break;
case VariantCrazyhouse:
case VariantBughouse:
pieces = FIDEArray;
SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
gameInfo.holdingsSize = 5;
break;
case VariantWildCastle:
pieces = FIDEArray;
/* !!?shuffle with kings guaranteed to be on d or e file */
shuffleOpenings = 1;
break;
case VariantNoCastle:
pieces = FIDEArray;
nrCastlingRights = 0;
/* !!?unconstrained back-rank shuffle */
shuffleOpenings = 1;
break;
}
overrule = 0;
if(appData.NrFiles >= 0) {
if(gameInfo.boardWidth != appData.NrFiles) overrule++;
gameInfo.boardWidth = appData.NrFiles;
}
if(appData.NrRanks >= 0) {
gameInfo.boardHeight = appData.NrRanks;
}
if(appData.holdingsSize >= 0) {
i = appData.holdingsSize;
if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
gameInfo.holdingsSize = i;
}
if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
if(pawnRow < 1) pawnRow = 1;
if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN ||
gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) pawnRow = 2;
if(gameInfo.variant == VariantChu) pawnRow = 3;
/* User pieceToChar list overrules defaults */
if(appData.pieceToCharTable != NULL)
SetCharTableEsc(pieceToChar, appData.pieceToCharTable, SUFFIXES);
for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
s = (ChessSquare) 0; /* account holding counts in guard band */
for( i=0; i<BOARD_HEIGHT; i++ )
initialPosition[i][j] = s;
if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
initialPosition[gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess][j] = pieces[0][j-gameInfo.holdingsWidth];
initialPosition[pawnRow][j] = WhitePawn;
initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
if(gameInfo.variant == VariantXiangqi) {
if(j&1) {
initialPosition[pawnRow][j] =
initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
initialPosition[2][j] = WhiteCannon;
initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
}
}
}
if(gameInfo.variant == VariantChu) {
if(j == (BOARD_WIDTH-2)/3 || j == BOARD_WIDTH - (BOARD_WIDTH+1)/3)
initialPosition[pawnRow+1][j] = WhiteCobra,
initialPosition[BOARD_HEIGHT-pawnRow-2][j] = BlackCobra;
for(i=1; i<pieceRows; i++) {
initialPosition[i][j] = pieces[2*i][j-gameInfo.holdingsWidth];
initialPosition[BOARD_HEIGHT-1-i][j] = pieces[2*i+1][j-gameInfo.holdingsWidth];
}
}
if(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
initialPosition[0][j] = WhiteRook;
initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
}
}
initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess)][j] = pieces[1][j-gameInfo.holdingsWidth];
}
if(gameInfo.variant == VariantChuChess) initialPosition[0][BOARD_WIDTH/2] = WhiteKing, initialPosition[BOARD_HEIGHT-1][BOARD_WIDTH/2-1] = BlackKing;
if( (gameInfo.variant == VariantShogi) && !overrule ) {
j=BOARD_LEFT+1;
initialPosition[1][j] = WhiteBishop;
initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
j=BOARD_RGHT-2;
initialPosition[1][j] = WhiteRook;
initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
}
if( nrCastlingRights == -1) {
/* [HGM] Build normal castling rights (must be done after board sizing!) */
/* This sets default castling rights from none to normal corners */
/* Variants with other castling rights must set them themselves above */
nrCastlingRights = 6;
initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
}
if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
if(gameInfo.variant == VariantGreat) { // promotion commoners
initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
}
if( gameInfo.variant == VariantSChess ) {
initialPosition[1][0] = BlackMarshall;
initialPosition[2][0] = BlackAngel;
initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
initialPosition[1][1] = initialPosition[2][1] =
initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
}
if (appData.debugMode) {
fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
}
if(shuffleOpenings) {
SetUpShuffle(initialPosition, appData.defaultFrcPosition);
startedFromSetupPosition = TRUE;
}
if(startedFromPositionFile) {
/* [HGM] loadPos: use PositionFile for every new game */
CopyBoard(initialPosition, filePosition);
for(i=0; i<nrCastlingRights; i++)
initialRights[i] = filePosition[CASTLING][i];
startedFromSetupPosition = TRUE;
}
if(*appData.men) LoadPieceDesc(appData.men);
CopyBoard(boards[0], initialPosition);
if(oldx != gameInfo.boardWidth ||
oldy != gameInfo.boardHeight ||
oldv != gameInfo.variant ||
oldh != gameInfo.holdingsWidth
)
InitDrawingSizes(-2 ,0);
oldv = gameInfo.variant;
if (redraw)
DrawPosition(TRUE, boards[currentMove]);
}
void
SendBoard (ChessProgramState *cps, int moveNum)
{
char message[MSG_SIZ];
if (cps->useSetboard) {
char* fen = PositionToFEN(moveNum, cps->fenOverride, 1);
snprintf(message, MSG_SIZ,"setboard %s\n", fen);
SendToProgram(message, cps);
free(fen);
} else {
ChessSquare *bp;
int i, j, left=0, right=BOARD_WIDTH;
/* Kludge to set black to move, avoiding the troublesome and now
* deprecated "black" command.
*/
if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn && !pieceDesc[WhitePawn] ? "a2a3\n" : "black\nforce\n", cps);
if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
SendToProgram("edit\n", cps);
SendToProgram("#\n", cps);
for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
bp = &boards[moveNum][i][left];
for (j = left; j < right; j++, bp++) {
if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
if ((int) *bp < (int) BlackPawn) {
if(j == BOARD_RGHT+1)
snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
else snprintf(message, MSG_SIZ, "%c%c%d\n", PieceToChar(*bp), AAA + j, ONE + i - '0');
if(message[0] == '+' || message[0] == '~') {
snprintf(message, MSG_SIZ,"%c%c%d+\n",
PieceToChar((ChessSquare)(DEMOTED(*bp))),
AAA + j, ONE + i - '0');
}
if(cps->alphaRank) { /* [HGM] shogi: translate coords */
message[1] = BOARD_RGHT - 1 - j + '1';
message[2] = BOARD_HEIGHT - 1 - i + 'a';
}
SendToProgram(message, cps);
}
}
}
SendToProgram("c\n", cps);
for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
bp = &boards[moveNum][i][left];
for (j = left; j < right; j++, bp++) {
if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
if (((int) *bp != (int) EmptySquare)
&& ((int) *bp >= (int) BlackPawn)) {
if(j == BOARD_LEFT-2)
snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
else snprintf(message,MSG_SIZ, "%c%c%d\n", ToUpper(PieceToChar(*bp)),
AAA + j, ONE + i - '0');
if(message[0] == '+' || message[0] == '~') {
snprintf(message, MSG_SIZ,"%c%c%d+\n",
PieceToChar((ChessSquare)(DEMOTED(*bp))),
AAA + j, ONE + i - '0');
}
if(cps->alphaRank) { /* [HGM] shogi: translate coords */
message[1] = BOARD_RGHT - 1 - j + '1';
message[2] = BOARD_HEIGHT - 1 - i + 'a';
}
SendToProgram(message, cps);
}
}
}
SendToProgram(".\n", cps);
}
setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
}
char exclusionHeader[MSG_SIZ];
int exCnt, excludePtr;
typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
static Exclusion excluTab[200];
static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
static void
WriteMap (int s)
{
int j;
for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
exclusionHeader[19] = s ? '-' : '+'; // update tail state
}
static void
ClearMap ()
{
safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
excludePtr = 24; exCnt = 0;
WriteMap(0);
}
static void
UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
{ // search given move in table of header moves, to know where it is listed (and add if not there), and update state
char buf[2*MOVE_LEN], *p;
Exclusion *e = excluTab;
int i;
for(i=0; i<exCnt; i++)
if(e[i].ff == fromX && e[i].fr == fromY &&
e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
if(i == exCnt) { // was not in exclude list; add it
CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
return; // abort
}
e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
excludePtr++; e[i].mark = excludePtr++;
for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
exCnt++;
}
exclusionHeader[e[i].mark] = state;
}
static int
ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
{ // include or exclude the given move, as specified by state ('+' or '-'), or toggle
char buf[MSG_SIZ];
int j, k;
ChessMove moveType;
if((signed char)promoChar == -1) { // kludge to indicate best move
if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
return 1; // if unparsable, abort
}
// update exclusion map (resolving toggle by consulting existing state)
k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
j = k%8; k >>= 3;
if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
excludeMap[k] |= 1<<j;
else excludeMap[k] &= ~(1<<j);
// update header
UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
// inform engine
snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
SendToBoth(buf);
return (state == '+');
}
static void
ExcludeClick (int index)
{
int i, j;
Exclusion *e = excluTab;
if(index < 25) { // none, best or tail clicked
if(index < 13) { // none: include all
WriteMap(0); // clear map
for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
SendToBoth("include all\n"); // and inform engine
} else if(index > 18) { // tail
if(exclusionHeader[19] == '-') { // tail was excluded
SendToBoth("include all\n");
WriteMap(0); // clear map completely
// now re-exclude selected moves
for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
} else { // tail was included or in mixed state
SendToBoth("exclude all\n");
WriteMap(0xFF); // fill map completely
// now re-include selected moves
j = 0; // count them
for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
}
} else { // best
ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
}
} else {
for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
break;
}
}
}
ChessSquare
DefaultPromoChoice (int white)
{
ChessSquare result;
if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
gameInfo.variant == VariantMakruk)
result = WhiteFerz; // no choice
else if(gameInfo.variant == VariantASEAN)
result = WhiteRook; // no choice
else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
result= WhiteKing; // in Suicide Q is the last thing we want
else if(gameInfo.variant == VariantSpartan)
result = white ? WhiteQueen : WhiteAngel;
else result = WhiteQueen;
if(!white) result = WHITE_TO_BLACK result;
return result;
}
static int autoQueen; // [HGM] oneclick
int
HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
{
/* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
/* [HGM] add Shogi promotions */
int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
ChessSquare piece, partner;
ChessMove moveType;
Boolean premove;
if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
!(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
return FALSE;
if(legal[toY][toX] == 4) return FALSE;
piece = boards[currentMove][fromY][fromX];
if(gameInfo.variant == VariantChu) {
promotionZoneSize = BOARD_HEIGHT/3;
if(legal[toY][toX] == 6) return FALSE; // no promotion if highlights deny it
highestPromotingPiece = (PieceToChar(piece) == '+' || PieceToChar(CHUPROMOTED(piece)) != '+') ? WhitePawn : WhiteKing;
} else if(gameInfo.variant == VariantShogi) {
promotionZoneSize = BOARD_HEIGHT/3 +(BOARD_HEIGHT == 8);
highestPromotingPiece = (int)WhiteAlfil;
} else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
promotionZoneSize = 3;
}
// Treat Lance as Pawn when it is not representing Amazon or Lance
if(gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu) {
if(piece == WhiteLance) piece = WhitePawn; else
if(piece == BlackLance) piece = BlackPawn;
}
// next weed out all moves that do not touch the promotion zone at all
if((int)piece >= BlackPawn) {
if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
return FALSE;
if(fromY < promotionZoneSize && gameInfo.variant == VariantChuChess) return FALSE;
highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
} else {
if( toY < BOARD_HEIGHT - promotionZoneSize &&
fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
if(fromY >= BOARD_HEIGHT - promotionZoneSize && gameInfo.variant == VariantChuChess)
return FALSE;
}
if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
// weed out mandatory Shogi promotions
if(gameInfo.variant == VariantShogi) {
if(piece >= BlackPawn) {
if(toY == 0 && piece == BlackPawn ||
toY == 0 && piece == BlackQueen ||
toY <= 1 && piece == BlackKnight) {
*promoChoice = '+';
return FALSE;
}
} else {
if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
*promoChoice = '+';
return FALSE;
}
}
}
// weed out obviously illegal Pawn moves
if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
// note we are not allowed to test for valid (non-)capture, due to premove
}
// we either have a choice what to promote to, or (in Shogi) whether to promote
if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
gameInfo.variant == VariantMakruk) {
ChessSquare p=BlackFerz; // no choice
while(p < EmptySquare) { //but make sure we use piece that exists
*promoChoice = PieceToChar(p++);
if(*promoChoice != '.') break;
}
if(!*engineVariant) return FALSE; // if used as parent variant there might be promotion choice
}
// no sense asking what we must promote to if it is going to explode...
if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
*promoChoice = PieceToChar(BlackQueen); // Queen as good as any
return FALSE;
}
// give caller the default choice even if we will not make it
*promoChoice = ToLower(PieceToChar(defaultPromoChoice));
partner = piece; // pieces can promote if the pieceToCharTable says so
if(IS_SHOGI(gameInfo.variant)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? '=' : '+'); // obsolete?
else if(Partner(&partner)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? NULLCHAR : '+');
if( sweepSelect && gameInfo.variant != VariantGreat
&& gameInfo.variant != VariantGrand
&& gameInfo.variant != VariantSuper) return FALSE;
if(autoQueen) return FALSE; // predetermined
// suppress promotion popup on illegal moves that are not premoves
premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
if(appData.testLegality && !premove) {
moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
fromY, fromX, toY, toX, IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantChuChess ? '+' : NULLCHAR);
if(moveType == IllegalMove) *promoChoice = NULLCHAR; // could be the fact we promoted was illegal
if(moveType != WhitePromotion && moveType != BlackPromotion)
return FALSE;
}
return TRUE;
}
int
InPalace (int row, int column)
{ /* [HGM] for Xiangqi */
if( (row < 3 || row > BOARD_HEIGHT-4) &&
column < (BOARD_WIDTH + 4)/2 &&
column > (BOARD_WIDTH - 5)/2 ) return TRUE;
return FALSE;
}
int
PieceForSquare (int x, int y)
{
if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
return -1;
else
return boards[currentMove][y][x];
}
int
OKToStartUserMove (int x, int y)
{
ChessSquare from_piece;
int white_piece;
if (matchMode) return FALSE;
if (gameMode == EditPosition) return TRUE;
if (x >= 0 && y >= 0)
from_piece = boards[currentMove][y][x];
else
from_piece = EmptySquare;
if (from_piece == EmptySquare) return FALSE;
white_piece = (int)from_piece >= (int)WhitePawn &&
(int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
switch (gameMode) {
case AnalyzeFile:
case TwoMachinesPlay:
case EndOfGame:
return FALSE;
case IcsObserving:
case IcsIdle:
return FALSE;
case MachinePlaysWhite:
case IcsPlayingBlack:
if (appData.zippyPlay) return FALSE;
if (white_piece) {
DisplayMoveError(_("You are playing Black"));
return FALSE;
}
break;
case MachinePlaysBlack:
case IcsPlayingWhite:
if (appData.zippyPlay) return FALSE;
if (!white_piece) {
DisplayMoveError(_("You are playing White"));
return FALSE;
}
break;
case PlayFromGameFile:
if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
case EditGame:
case AnalyzeMode:
if (!white_piece && WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is White's turn"));
return FALSE;
}
if (white_piece && !WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is Black's turn"));
return FALSE;
}
if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
/* Editing correspondence game history */
/* Could disallow this or prompt for confirmation */
cmailOldMove = -1;
}
break;
case BeginningOfGame:
if (appData.icsActive) return FALSE;
if (!appData.noChessProgram) {
if (!white_piece) {
DisplayMoveError(_("You are playing White"));
return FALSE;
}
}
break;
case Training:
if (!white_piece && WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is White's turn"));
return FALSE;
}
if (white_piece && !WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is Black's turn"));
return FALSE;
}
break;
default:
case IcsExamining:
break;
}
if (currentMove != forwardMostMove && gameMode != AnalyzeMode
&& gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
&& gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
&& gameMode != AnalyzeFile && gameMode != Training) {
DisplayMoveError(_("Displayed position is not current"));
return FALSE;
}
return TRUE;
}
Boolean
OnlyMove (int *x, int *y, Boolean captures)
{
DisambiguateClosure cl;
if (appData.zippyPlay || !appData.testLegality) return FALSE;
switch(gameMode) {
case MachinePlaysBlack:
case IcsPlayingWhite:
case BeginningOfGame:
if(!WhiteOnMove(currentMove)) return FALSE;
break;
case MachinePlaysWhite:
case IcsPlayingBlack:
if(WhiteOnMove(currentMove)) return FALSE;
break;
case EditGame:
break;
default:
return FALSE;
}
cl.pieceIn = EmptySquare;
cl.rfIn = *y;
cl.ffIn = *x;
cl.rtIn = -1;
cl.ftIn = -1;
cl.promoCharIn = NULLCHAR;
Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
if( cl.kind == NormalMove ||
cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
fromX = cl.ff;
fromY = cl.rf;
*x = cl.ft;
*y = cl.rt;
return TRUE;
}
if(cl.kind != ImpossibleMove) return FALSE;
cl.pieceIn = EmptySquare;
cl.rfIn = -1;
cl.ffIn = -1;
cl.rtIn = *y;
cl.ftIn = *x;
cl.promoCharIn = NULLCHAR;
Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
if( cl.kind == NormalMove ||
cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
fromX = cl.ff;
fromY = cl.rf;
*x = cl.ft;
*y = cl.rt;
autoQueen = TRUE; // act as if autoQueen on when we click to-square
return TRUE;
}
return FALSE;
}
FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
int lastLoadGameUseList = FALSE;
char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
ChessMove lastLoadGameStart = EndOfFile;
int doubleClick;
Boolean addToBookFlag;
static Board rightsBoard, nullBoard;
void
UserMoveEvent (int fromX, int fromY, int toX, int toY, int promoChar)
{
ChessMove moveType;
ChessSquare pup;
int ff=fromX, rf=fromY, ft=toX, rt=toY;
/* Check if the user is playing in turn. This is complicated because we
let the user "pick up" a piece before it is his turn. So the piece he
tried to pick up may have been captured by the time he puts it down!
Therefore we use the color the user is supposed to be playing in this
test, not the color of the piece that is currently on the starting
square---except in EditGame mode, where the user is playing both
sides; fortunately there the capture race can't happen. (It can
now happen in IcsExamining mode, but that's just too bad. The user
will get a somewhat confusing message in that case.)
*/
switch (gameMode) {
case AnalyzeFile:
case TwoMachinesPlay:
case EndOfGame:
case IcsObserving:
case IcsIdle:
/* We switched into a game mode where moves are not accepted,
perhaps while the mouse button was down. */
return;
case MachinePlaysWhite:
/* User is moving for Black */
if (WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is White's turn"));
return;
}
break;
case MachinePlaysBlack:
/* User is moving for White */
if (!WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is Black's turn"));
return;
}
break;
case PlayFromGameFile:
if(!shiftKey ||!appData.variations) return; // [HGM] only variations
case EditGame:
case IcsExamining:
case BeginningOfGame:
case AnalyzeMode:
case Training:
if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
(int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
/* User is moving for Black */
if (WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is White's turn"));
return;
}
} else {
/* User is moving for White */
if (!WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is Black's turn"));
return;
}
}
break;
case IcsPlayingBlack:
/* User is moving for Black */
if (WhiteOnMove(currentMove)) {
if (!appData.premove) {
DisplayMoveError(_("It is White's turn"));
} else if (toX >= 0 && toY >= 0) {
premoveToX = toX;
premoveToY = toY;
premoveFromX = fromX;
premoveFromY = fromY;
premovePromoChar = promoChar;
gotPremove = 1;
if (appData.debugMode)
fprintf(debugFP, "Got premove: fromX %d,"
"fromY %d, toX %d, toY %d\n",
fromX, fromY, toX, toY);
}
DrawPosition(TRUE, boards[currentMove]); // [HGM] repair animation damage done by premove (in particular emptying from-square)
return;
}
break;
case IcsPlayingWhite:
/* User is moving for White */
if (!WhiteOnMove(currentMove)) {
if (!appData.premove) {
DisplayMoveError(_("It is Black's turn"));
} else if (toX >= 0 && toY >= 0) {
premoveToX = toX;
premoveToY = toY;
premoveFromX = fromX;
premoveFromY = fromY;
premovePromoChar = promoChar;
gotPremove = 1;
if (appData.debugMode)
fprintf(debugFP, "Got premove: fromX %d,"
"fromY %d, toX %d, toY %d\n",
fromX, fromY, toX, toY);
}
DrawPosition(TRUE, boards[currentMove]);
return;
}
break;
default:
break;
case EditPosition:
/* EditPosition, empty square, or different color piece;
click-click move is possible */
if (toX == -2 || toY == -2) {
boards[0][fromY][fromX] = (boards[0][fromY][fromX] == EmptySquare ? DarkSquare : EmptySquare);
DrawPosition(FALSE, boards[currentMove]);
return;
} else if (toX >= 0 && toY >= 0) {
if(!appData.pieceMenu && toX == fromX && toY == fromY && boards[0][rf][ff] != EmptySquare) {
ChessSquare p = boards[0][rf][ff];
if(PieceToChar(p) == '+') gatingPiece = CHUDEMOTED(p); else
if(PieceToChar(CHUPROMOTED(p)) =='+') gatingPiece = CHUPROMOTED(p); else
if(p == WhiteKing || p == BlackKing || p == WhiteRook || p == BlackRook || p == WhitePawn || p == BlackPawn) {
int n = rightsBoard[toY][toX] ^= 1; // toggle virginity of K or R
DisplayMessage("", n ? _("rights granted") : _("rights revoked"));
gatingPiece = p;
}
} else rightsBoard[toY][toX] = 0; // revoke rights on moving
boards[0][toY][toX] = boards[0][fromY][fromX];
if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
if(boards[0][fromY][0] != EmptySquare) {
if(boards[0][fromY][1]) boards[0][fromY][1]--;
if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
}
} else
if(fromX == BOARD_RGHT+1) {
if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
}
} else
boards[0][fromY][fromX] = gatingPiece;
ClearHighlights();
DrawPosition(FALSE, boards[currentMove]);
return;
}
return;
}
if((toX < 0 || toY < 0) && (fromY != DROP_RANK || fromX != EmptySquare)) return;
pup = boards[currentMove][toY][toX];
/* [HGM] If move started in holdings, it means a drop. Convert to standard form */
if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
if( pup != EmptySquare ) return;
moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
// holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
while(PieceToChar(fromX) == '.' || PieceToChar(fromX) == '+' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
fromY = DROP_RANK;
}
/* [HGM] always test for legality, to get promotion info */
moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
fromY, fromX, toY, toX, promoChar);
if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame || PosFlags(0) & F_NULL_MOVE)) moveType = NormalMove;
if(moveType == IllegalMove && legal[toY][toX] > 1) moveType = NormalMove; // someone explicitly told us this move is legal
/* [HGM] but possibly ignore an IllegalMove result */
if (appData.testLegality) {
if (moveType == IllegalMove || moveType == ImpossibleMove) {
DisplayMoveError(_("Illegal move"));
return;
}
}
if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
ClearPremoveHighlights(); // was included
else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
DrawPosition(FALSE, NULL);
return;
}
if(addToBookFlag) { // adding moves to book
char buf[MSG_SIZ], move[MSG_SIZ];
CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, move);
if(killX >= 0) snprintf(move, MSG_SIZ, "%c%dx%c%d-%c%d%c", fromX + AAA, fromY + ONE - '0',
killX + AAA, killY + ONE - '0', toX + AAA, toY + ONE - '0', promoChar);
snprintf(buf, MSG_SIZ, " 0.0%% 1 %s\n", move);
AddBookMove(buf);
addToBookFlag = FALSE;
ClearHighlights();
return;
}
FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
}
/* Common tail of UserMoveEvent and DropMenuEvent */
int
FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
{
char *bookHit = 0;
if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
// [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
if(WhiteOnMove(currentMove)) {
if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
} else {
if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
}
}
/* [HGM] <popupFix> kludge to avoid having to know the exact promotion
move type in caller when we know the move is a legal promotion */
if(moveType == NormalMove && promoChar)
moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
/* [HGM] <popupFix> The following if has been moved here from
UserMoveEvent(). Because it seemed to belong here (why not allow
piece drops in training games?), and because it can only be
performed after it is known to what we promote. */
if (gameMode == Training) {
/* compare the move played on the board to the next move in the
* game. If they match, display the move and the opponent's response.
* If they don't match, display an error message.
*/
int saveAnimate;
Board testBoard;
CopyBoard(testBoard, boards[currentMove]);
ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
if (CompareBoards(testBoard, boards[currentMove+1])) {
ForwardInner(currentMove+1);
/* Autoplay the opponent's response.
* if appData.animate was TRUE when Training mode was entered,
* the response will be animated.
*/
saveAnimate = appData.animate;
appData.animate = animateTraining;
ForwardInner(currentMove+1);
appData.animate = saveAnimate;
/* check for the end of the game */
if (currentMove >= forwardMostMove) {
gameMode = PlayFromGameFile;
ModeHighlight();
SetTrainingModeOff();
DisplayInformation(_("End of game"));
}
} else {
DisplayError(_("Incorrect move"), 0);
}
return 1;
}
/* Ok, now we know that the move is good, so we can kill
the previous line in Analysis Mode */
if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
&& currentMove < forwardMostMove) {
if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
else forwardMostMove = currentMove;
}
ClearMap();
/* If we need the chess program but it's dead, restart it */
ResurrectChessProgram();
/* A user move restarts a paused game*/
if (pausing)
PauseEvent();
thinkOutput[0] = NULLCHAR;
MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
return 1;
}
if (gameMode == BeginningOfGame) {
if (appData.noChessProgram) {
gameMode = EditGame;
SetGameInfo();
} else {
char buf[MSG_SIZ];
gameMode = MachinePlaysBlack;
StartClocks();
SetGameInfo();
snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
DisplayTitle(buf);
if (first.sendName) {
snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
SendToProgram(buf, &first);
}
StartClocks();
}
ModeHighlight();
}
/* Relay move to ICS or chess engine */
if (appData.icsActive) {
if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
gameMode == IcsExamining) {
if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
SendToICS("draw ");
SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
}
// also send plain move, in case ICS does not understand atomic claims
SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
ics_user_moved = 1;
}
} else {
if (first.sendTime && (gameMode == BeginningOfGame ||
gameMode == MachinePlaysWhite ||
gameMode == MachinePlaysBlack)) {
SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
}
if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
// [HGM] book: if program might be playing, let it use book
bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
first.maybeThinking = TRUE;
} else if(fromY == DROP_RANK && fromX == EmptySquare) {
if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
SendBoard(&first, currentMove+1);
if(second.analyzing) {
if(!second.useSetboard) SendToProgram("undo\n", &second);
SendBoard(&second, currentMove+1);
}
} else {
SendMoveToProgram(forwardMostMove-1, &first);
if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
}
if (currentMove == cmailOldMove + 1) {
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
}
}
ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
switch (gameMode) {
case EditGame:
if(appData.testLegality)
switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
case MT_NONE:
case MT_CHECK:
break;
case MT_CHECKMATE:
case MT_STAINMATE:
if (WhiteOnMove(currentMove)) {
GameEnds(BlackWins, "Black mates", GE_PLAYER);
} else {
GameEnds(WhiteWins, "White mates", GE_PLAYER);
}
break;
case MT_STALEMATE:
GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
break;
}
break;
case MachinePlaysBlack:
case MachinePlaysWhite:
/* disable certain menu options while machine is thinking */
SetMachineThinkingEnables();
break;
default:
break;
}
userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
promoDefaultAltered = FALSE; // [HGM] fall back on default choice
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
HandleMachineMove(bookMove, &first);
}
return 1;
}
void
MarkByFEN(char *fen)
{
int r, f;
if(!appData.markers || !appData.highlightDragging) return;
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) legal[r][f] = marker[r][f] = 0;
r=BOARD_HEIGHT-1-deadRanks; f=BOARD_LEFT;
while(*fen) {
int s = 0;
if(*fen == 'M') legal[r][f] = 2; else // request promotion choice
if(*fen == 'B') legal[r][f] = 4; else // request auto-promotion to victim
if(*fen >= 'A' && *fen <= 'Z') legal[r][f] = 6; else
if(*fen >= 'a' && *fen <= 'z') *fen += 'A' - 'a';
if(*fen == '/' && f > BOARD_LEFT) f = BOARD_LEFT, r--; else
if(*fen == 'T') marker[r][f++] = 0; else
if(*fen == 'Y') marker[r][f++] = 1; else
if(*fen == 'G') marker[r][f++] = 3; else
if(*fen == 'B') marker[r][f++] = 4; else
if(*fen == 'C') marker[r][f++] = 5; else
if(*fen == 'M') marker[r][f++] = 6; else
if(*fen == 'W') marker[r][f++] = 7; else
if(*fen == 'D') marker[r][f++] = 8; else
if(*fen == 'R') marker[r][f++] = 2; else {
while(*fen <= '9' && *fen >= '0') s = 10*s + *fen++ - '0';
f += s; fen -= s>0;
}
while(f >= BOARD_RGHT) f -= BOARD_RGHT - BOARD_LEFT, r--;
if(r < 0) break;
fen++;
}
DrawPosition(TRUE, NULL);
}
static char baseMarker[BOARD_RANKS][BOARD_FILES], baseLegal[BOARD_RANKS][BOARD_FILES];
void
Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
{
typedef char Markers[BOARD_RANKS][BOARD_FILES];
Markers *m = (Markers *) closure;
if(rf == fromY && ff == fromX && (killX < 0 ? !(rt == rf && ft == ff) && legNr & 1 :
kill2X < 0 ? rt == killY && ft == killX || legNr & 2 : rt == killY && ft == killX || legNr & 4))
(*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
|| kind == WhiteCapturesEnPassant
|| kind == BlackCapturesEnPassant) + 3*(kind == FirstLeg && (killX < 0 & legNr || legNr & 2 && kill2X < 0)), legal[rt][ft] = 3;
else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3, legal[rt][ft] = 3;
}
static int hoverSavedValid;
void
MarkTargetSquares (int clear)
{
int x, y, sum=0;
if(clear) { // no reason to ever suppress clearing
for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) sum += marker[y][x], marker[y][x] = 0;
hoverSavedValid = 0;
if(!sum || clear < 0) return; // nothing was cleared,no redraw needed
} else {
int capt = 0;
if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
!appData.testLegality && !pieceDefs || gameMode == EditPosition) return;
GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
if(PosFlags(0) & F_MANDATORY_CAPTURE) {
for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
if(capt)
for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
}
}
DrawPosition(FALSE, NULL);
}
int
Explode (Board board, int fromX, int fromY, int toX, int toY)
{
if(gameInfo.variant == VariantAtomic &&
(board[toY][toX] != EmptySquare || // capture?
toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
board[fromY][fromX] == BlackPawn )
)) {
AnimateAtomicCapture(board, fromX, fromY, toX, toY);
return TRUE;
}
return FALSE;
}
ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
int
CanPromote (ChessSquare piece, int y)
{
int zone = (gameInfo.variant == VariantChuChess ? 3 : 1);
if(gameMode == EditPosition) return FALSE; // no promotions when editing position
// some variants have fixed promotion piece, no promotion at all, or another selection mechanism
if(IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantXiangqi ||
gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
gameInfo.variant == VariantMakruk) && !*engineVariant) return FALSE;
return (piece == BlackPawn && y <= zone ||
piece == WhitePawn && y >= BOARD_HEIGHT-1-zone ||
piece == BlackLance && y <= zone ||
piece == WhiteLance && y >= BOARD_HEIGHT-1-zone );
}
void
HoverEvent (int xPix, int yPix, int x, int y)
{
static int oldX = -1, oldY = -1, oldFromX = -1, oldFromY = -1;
int r, f;
if(!first.highlight) return;
if(fromX != oldFromX || fromY != oldFromY) oldX = oldY = -1; // kludge to fake entry on from-click
if(x == oldX && y == oldY) return; // only do something if we enter new square
oldFromX = fromX; oldFromY = fromY;
if(oldX == -1 && oldY == -1 && x == fromX && y == fromY) { // record markings after from-change
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
baseMarker[r][f] = marker[r][f], baseLegal[r][f] = legal[r][f];
hoverSavedValid = 1;
} else if(oldX != x || oldY != y) {
// [HGM] lift: entered new to-square; redraw arrow, and inform engine
if(hoverSavedValid) // don't restore markers that are supposed to be cleared
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
marker[r][f] = baseMarker[r][f], legal[r][f] = baseLegal[r][f];
if((marker[y][x] == 2 || marker[y][x] == 6) && legal[y][x]) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "hover %c%d\n", x + AAA, y + ONE - '0');
SendToProgram(buf, &first);
}
oldX = x; oldY = y;
// SetHighlights(fromX, fromY, x, y);
}
}
void ReportClick(char *action, int x, int y)
{
char buf[MSG_SIZ]; // Inform engine of what user does
int r, f;
if(action[0] == 'l') // mark any target square of a lifted piece as legal to-square, clear markers
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
legal[r][f] = !pieceDefs || !appData.markers, marker[r][f] = 0;
if(!first.highlight || gameMode == EditPosition) return;
snprintf(buf, MSG_SIZ, "%s %c%d%s\n", action, x+AAA, y+ONE-'0', controlKey && action[0]=='p' ? "," : "");
SendToProgram(buf, &first);
}
Boolean right; // instructs front-end to use button-1 events as if they were button 3
Boolean deferChoice;
void
LeftClick (ClickType clickType, int xPix, int yPix)
{
int x, y;
static Boolean saveAnimate;
static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0, flashing = 0, saveFlash;
char promoChoice = NULLCHAR;
ChessSquare piece;
static TimeMark lastClickTime, prevClickTime;
if(flashing) return;
if(!deferChoice) { // when called for a retry, skip everything to the point where we left off
x = EventToSquare(xPix, BOARD_WIDTH);
y = EventToSquare(yPix, BOARD_HEIGHT);
if (!flipView && y >= 0) {
y = BOARD_HEIGHT - 1 - y;
}
if (flipView && x >= 0) {
x = BOARD_WIDTH - 1 - x;
}
if(appData.monoMouse && gameMode == EditPosition && fromX < 0 && clickType == Press && boards[currentMove][y][x] == EmptySquare) {
static int dummy;
RightClick(clickType, xPix, yPix, &dummy, &dummy);
right = TRUE;
return;
}
if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
if (clickType == Press) ErrorPopDown();
lastClickType = clickType, lastLeftX = xPix, lastLeftY = yPix; // [HGM] alien: remember state
if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
defaultPromoChoice = promoSweep;
promoSweep = EmptySquare; // terminate sweep
promoDefaultAltered = TRUE;
if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
}
if(promotionChoice) { // we are waiting for a click to indicate promotion piece
if(clickType == Release) return; // ignore upclick of click-click destination
promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
if(gameInfo.holdingsWidth &&
(WhiteOnMove(currentMove)
? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
: x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
// click in right holdings, for determining promotion piece
ChessSquare p = boards[currentMove][y][x];
if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
fromX = fromY = -1;
return;
}
}
DrawPosition(FALSE, boards[currentMove]);
return;
}
/* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
if(clickType == Press
&& ( x == BOARD_LEFT-1 || x == BOARD_RGHT
|| x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
|| x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
return;
if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
// could be static click on premove from-square: abort premove
gotPremove = 0;
ClearPremoveHighlights();
}
if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
defaultPromoChoice = DefaultPromoChoice(side);
}
autoQueen = appData.alwaysPromoteToQueen;
if (fromX == -1) {
int originalY = y;
gatingPiece = EmptySquare;
if (clickType != Press) {
if(dragging) { // [HGM] from-square must have been reset due to game end since last press
DragPieceEnd(xPix, yPix); dragging = 0;
DrawPosition(FALSE, NULL);
}
return;
}
doubleClick = FALSE;
if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
}
fromX = x; fromY = y; toX = toY = killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
// even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
/* First square */
if (OKToStartUserMove(fromX, fromY)) {
second = 0;
ReportClick("lift", x, y);
MarkTargetSquares(0);
if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
promoSweep = defaultPromoChoice;
selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
Sweep(0); // Pawn that is going to promote: preview promotion piece
DisplayMessage("", _("Pull pawn backwards to under-promote"));
}
if (appData.highlightDragging) {
SetHighlights(fromX, fromY, -1, -1);
} else {
ClearHighlights();
}
} else fromX = fromY = -1;
return;
}
}
/* fromX != -1 */
if (clickType == Press && gameMode != EditPosition) {
ChessSquare fromP;
ChessSquare toP;
int frc;
// ignore off-board to clicks
if(y < 0 || x < 0) return;
/* Check if clicking again on the same color piece */
fromP = boards[currentMove][fromY][fromX];
toP = boards[currentMove][y][x];
frc = appData.fischerCastling || gameInfo.variant == VariantSChess;
if( (killX < 0 || x != fromX || y != fromY) && // [HGM] lion: do not interpret igui as deselect!
marker[y][x] == 0 && // if engine told we can move to here, do it even if own piece
((WhitePawn <= fromP && fromP <= WhiteKing &&
WhitePawn <= toP && toP <= WhiteKing &&
!(fromP == WhiteKing && toP == WhiteRook && frc) &&
!(fromP == WhiteRook && toP == WhiteKing && frc)) ||
(BlackPawn <= fromP && fromP <= BlackKing &&
BlackPawn <= toP && toP <= BlackKing &&
!(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
!(fromP == BlackKing && toP == BlackRook && frc)))) {
/* Clicked again on same color piece -- changed his mind */
second = (x == fromX && y == fromY);
killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
second = FALSE; // first double-click rather than scond click
doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
}
promoDefaultAltered = FALSE;
if(!second) MarkTargetSquares(1);
if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
if (appData.highlightDragging) {
SetHighlights(x, y, -1, -1);
} else {
ClearHighlights();
}
if (OKToStartUserMove(x, y)) {
if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
(fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
gatingPiece = boards[currentMove][fromY][fromX];
else gatingPiece = doubleClick ? fromP : EmptySquare;
fromX = x;
fromY = y; dragging = 1;
if(!second) ReportClick("lift", x, y);
MarkTargetSquares(0);
DragPieceBegin(xPix, yPix, FALSE);
if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
promoSweep = defaultPromoChoice;
selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
Sweep(0); // Pawn that is going to promote: preview promotion piece
}
}
}
if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
second = FALSE;
}
// ignore clicks on holdings
if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
}
if(x == fromX && y == fromY && clickType == Press && gameMode == EditPosition && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
gatingPiece = boards[currentMove][fromY][fromX]; // prepare to copy rather than move
DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
return;
}
if (clickType == Release && x == fromX && y == fromY && killX < 0 && !sweepSelecting) {
DragPieceEnd(xPix, yPix); dragging = 0;
if(clearFlag) {
// a deferred attempt to click-click move an empty square on top of a piece
boards[currentMove][y][x] = EmptySquare;
ClearHighlights();
DrawPosition(FALSE, boards[currentMove]);
fromX = fromY = -1; clearFlag = 0;
return;
}
if (appData.animateDragging) {
/* Undo animation damage if any */
DrawPosition(FALSE, NULL);
}
if (second) {
/* Second up/down in same square; just abort move */
second = 0;
fromX = fromY = -1;
gatingPiece = EmptySquare;
ClearHighlights();
gotPremove = 0;
ClearPremoveHighlights();
MarkTargetSquares(-1);
DrawPosition(FALSE, NULL); // make user highlights are drawn (and deferred marker clearing)
} else {
/* First upclick in same square; start click-click mode */
SetHighlights(x, y, -1, -1);
}
return;
}
clearFlag = 0;
if(gameMode != EditPosition && !appData.testLegality && !legal[y][x] &&
fromX >= BOARD_LEFT && fromX < BOARD_RGHT && (x != killX || y != killY) && !sweepSelecting) {
if(dragging) DragPieceEnd(xPix, yPix), dragging = 0;
DisplayMessage(_("only marked squares are legal"),"");
DrawPosition(TRUE, NULL);
return; // ignore to-click
}
/* we now have a different from- and (possibly off-board) to-square */
/* Completed move */
if(!sweepSelecting) {
toX = x;
toY = y;
}
piece = boards[currentMove][fromY][fromX];
saveAnimate = appData.animate;
if (clickType == Press) {
if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
// must be Edit Position mode with empty-square selected
fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
return;
}
if(dragging == 2) { // [HGM] lion: just turn buttonless drag into normal drag, and let release to the job
return;
}
if(x == killX && y == killY) { // second click on this square, which was selected as first-leg target
killX = kill2X; killY = kill2Y; kill2X = kill2Y = -1; // this informs us no second leg is coming, so treat as to-click without intermediate
} else
if(marker[y][x] == 5) return; // [HGM] lion: to-click on cyan square; defer action to release
if(legal[y][x] == 2 || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
if(appData.sweepSelect) {
promoSweep = defaultPromoChoice;
if(gameInfo.variant != VariantChuChess && PieceToChar(CHUPROMOTED(piece)) == '+') promoSweep = CHUPROMOTED(piece);
selectFlag = 0; lastX = xPix; lastY = yPix;
ReportClick("put", x, y); // extra put to prompt engine for 'choice' command
saveFlash = appData.flashCount; appData.flashCount = 0;
Sweep(0); // Pawn that is going to promote: preview promotion piece
sweepSelecting = 1;
DisplayMessage("", _("Pull pawn backwards to under-promote"));
MarkTargetSquares(1);
}
return; // promo popup appears on up-click
}
/* Finish clickclick move */
if (appData.animate || appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
} else {
ClearHighlights();
}
MarkTargetSquares(1);
} else if(sweepSelecting) { // this must be the up-click corresponding to the down-click that started the sweep
sweepSelecting = 0; appData.animate = FALSE; // do not animate, a selected piece already on to-square
*promoRestrict = 0; appData.flashCount = saveFlash;
if (appData.animate || appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
} else {
ClearHighlights();
}
MarkTargetSquares(1);
} else {
#if 0
// [HGM] this must be done after the move is made, as with arrow it could lead to a board redraw with piece still on from square
/* Finish drag move */
if (appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
} else {
ClearHighlights();
}
#endif
if(PieceToChar(CHUPROMOTED(boards[currentMove][fromY][fromX])) == '+')
defaultPromoChoice = CHUPROMOTED(boards[currentMove][fromY][fromX]);
if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
if(marker[y][x] == 5) { // [HGM] lion: this was the release of a to-click or drag on a cyan square
dragging *= 2; // flag button-less dragging if we are dragging
MarkTargetSquares(1);
if(x == killX && y == killY) killX = kill2X, killY = kill2Y, kill2X = kill2Y = -1; // cancel last kill
else {
kill2X = killX; kill2Y = killY;
killX = x; killY = y; // remember this square as intermediate
ReportClick("put", x, y); // and inform engine
ReportClick("lift", x, y);
MarkTargetSquares(0);
return;
}
}
DragPieceEnd(xPix, yPix); dragging = 0;
/* Don't animate move and drag both */
appData.animate = FALSE;
MarkTargetSquares(-1); // -1 defers displaying marker change to prevent piece reappearing on from-square!
}
// moves into holding are invalid for now (except in EditPosition, adapting to-square)
if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
ChessSquare piece = boards[currentMove][fromY][fromX];
if(gameMode == EditPosition && piece != EmptySquare &&
fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
int n;
if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
n = PieceToNumber(piece - (int)BlackPawn);
if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
} else
if(x == BOARD_RGHT+1 && piece < BlackPawn) {
n = PieceToNumber(piece);
if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
boards[currentMove][n][BOARD_WIDTH-1] = piece;
boards[currentMove][n][BOARD_WIDTH-2]++;
}
boards[currentMove][fromY][fromX] = EmptySquare;
}
ClearHighlights();
fromX = fromY = -1;
MarkTargetSquares(1);
DrawPosition(TRUE, boards[currentMove]);
return;
}
// off-board moves should not be highlighted
if(x < 0 || y < 0) {
ClearHighlights();
DrawPosition(FALSE, NULL);
} else ReportClick("put", x, y);
if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
}
if(legal[toY][toX] == 2) { // highlight-induced promotion
if(piece == defaultPromoChoice) promoChoice = NULLCHAR; // deferral
else promoChoice = ToLower(PieceToChar(defaultPromoChoice));
} else if(legal[toY][toX] == 4) { // blue target square: engine must supply promotion choice
if(!*promoRestrict) { // but has not done that yet
deferChoice = TRUE; // set up retry for when it does
return; // and wait for that
}
promoChoice = ToLower(*promoRestrict); // force engine's choice
deferChoice = FALSE;
}
if (legal[toY][toX] == 2 && !appData.sweepSelect || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
SetHighlights(fromX, fromY, toX, toY);
MarkTargetSquares(1);
if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
// [HGM] super: promotion to captured piece selected from holdings
ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
promotionChoice = TRUE;
// kludge follows to temporarily execute move on display, without promoting yet
boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
boards[currentMove][toY][toX] = p;
DrawPosition(FALSE, boards[currentMove]);
boards[currentMove][fromY][fromX] = p; // take back, but display stays
boards[currentMove][toY][toX] = q;
DisplayMessage("Click in holdings to choose piece", "");
return;
}
DrawPosition(FALSE, NULL); // shows piece on from-square during promo popup
PromotionPopUp(promoChoice);
} else {
int oldMove = currentMove;
flashing = 1; // prevent recursive calling (by release of to-click) while flashing piece
UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
if (!appData.highlightLastMove || gotPremove) ClearHighlights();
if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY), DrawPosition(FALSE, NULL);
if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
Explode(boards[currentMove-1], fromX, fromY, toX, toY))
DrawPosition(TRUE, boards[currentMove]);
else DrawPosition(FALSE, NULL);
fromX = fromY = -1;
flashing = 0;
}
appData.animate = saveAnimate;
if (appData.animate || appData.animateDragging) {
/* Undo animation damage if needed */
// DrawPosition(FALSE, NULL);
}
}
int
RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
{ // front-end-free part taken out of PieceMenuPopup
int whichMenu; int xSqr, ySqr;
if(seekGraphUp) { // [HGM] seekgraph
if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
return -2;
}
if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
&& !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
if(action == Press) {
originalFlip = flipView;
flipView = !flipView; // temporarily flip board to see game from partners perspective
DrawPosition(TRUE, partnerBoard);
DisplayMessage(partnerStatus, "");
partnerUp = TRUE;
} else if(action == Release) {
flipView = originalFlip;
DrawPosition(TRUE, boards[currentMove]);
partnerUp = FALSE;
}
return -2;
}
xSqr = EventToSquare(x, BOARD_WIDTH);
ySqr = EventToSquare(y, BOARD_HEIGHT);
if (action == Release) {
if(pieceSweep != EmptySquare) {
EditPositionMenuEvent(pieceSweep, toX, toY);
pieceSweep = EmptySquare;
} else UnLoadPV(); // [HGM] pv
}
if (action != Press) return -2; // return code to be ignored
switch (gameMode) {
case IcsExamining:
if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
case EditPosition:
if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
if (xSqr < 0 || ySqr < 0) return -1;
if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
toX = xSqr; toY = ySqr; lastX = x, lastY = y;
if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
NextPiece(0);
return 2; // grab
case IcsObserving:
if(!appData.icsEngineAnalyze) return -1;
case IcsPlayingWhite:
case IcsPlayingBlack:
if(!appData.zippyPlay) goto noZip;
case AnalyzeMode:
case AnalyzeFile:
case MachinePlaysWhite:
case MachinePlaysBlack:
case TwoMachinesPlay: // [HGM] pv: use for showing PV
if (!appData.dropMenu) {
LoadPV(x, y);
return 2; // flag front-end to grab mouse events
}
if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
case EditGame:
noZip:
if (xSqr < 0 || ySqr < 0) return -1;
if (!appData.dropMenu || appData.testLegality &&
gameInfo.variant != VariantBughouse &&
gameInfo.variant != VariantCrazyhouse) return -1;
whichMenu = 1; // drop menu
break;
default:
return -1;
}
if (((*fromX = xSqr) < 0) ||
((*fromY = ySqr) < 0)) {
*fromX = *fromY = -1;
return -1;
}
if (flipView)
*fromX = BOARD_WIDTH - 1 - *fromX;
else
*fromY = BOARD_HEIGHT - 1 - *fromY;
return whichMenu;
}
void
Wheel (int dir, int x, int y)
{
if(gameMode == EditPosition) {
int xSqr = EventToSquare(x, BOARD_WIDTH);
int ySqr = EventToSquare(y, BOARD_HEIGHT);
if(ySqr < 0 || xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return;
if(flipView) xSqr = BOARD_WIDTH - 1 - xSqr; else ySqr = BOARD_HEIGHT - 1 - ySqr;
do {
boards[currentMove][ySqr][xSqr] += dir;
if((int) boards[currentMove][ySqr][xSqr] < WhitePawn) boards[currentMove][ySqr][xSqr] = BlackKing;
if((int) boards[currentMove][ySqr][xSqr] > BlackKing) boards[currentMove][ySqr][xSqr] = WhitePawn;
} while(PieceToChar(boards[currentMove][ySqr][xSqr]) == '.');
DrawPosition(FALSE, boards[currentMove]);
} else if(dir > 0) ForwardEvent(); else BackwardEvent();
}
void
SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
{
// char * hint = lastHint;
FrontEndProgramStats stats;
stats.which = cps == &first ? 0 : 1;
stats.depth = cpstats->depth;
stats.nodes = cpstats->nodes;
stats.score = cpstats->score;
stats.time = cpstats->time;
stats.pv = cpstats->movelist;
stats.hint = lastHint;
stats.an_move_index = 0;
stats.an_move_count = 0;
if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
stats.hint = cpstats->move_name;
stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
stats.an_move_count = cpstats->nr_moves;
}
if(stats.pv && stats.pv[0]) safeStrCpy(lastPV[stats.which], stats.pv, sizeof(lastPV[stats.which])/sizeof(lastPV[stats.which][0])); // [HGM] pv: remember last PV of each
if( gameMode == AnalyzeMode && stats.pv && stats.pv[0]
&& appData.analysisBell && stats.time >= 100*appData.analysisBell ) RingBell();
SetProgramStats( &stats );
}
void
ClearEngineOutputPane (int which)
{
static FrontEndProgramStats dummyStats;
dummyStats.which = which;
dummyStats.pv = "#";
SetProgramStats( &dummyStats );
}
#define MAXPLAYERS 500
char *
TourneyStandings (int display)
{
int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
char result, *p, *names[MAXPLAYERS];
if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
names[0] = p = strdup(appData.participants);
while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
while(result = appData.results[nr]) {
color = Pairing(nr, nPlayers, &w, &b, &dummy);
if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
wScore = bScore = 0;
switch(result) {
case '+': wScore = 2; break;
case '-': bScore = 2; break;
case '=': wScore = bScore = 1; break;
case ' ':
case '*': return strdup("busy"); // tourney not finished
}
score[w] += wScore;
score[b] += bScore;
games[w]++;
games[b]++;
nr++;
}
if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
for(w=0; w<nPlayers; w++) {
bScore = -1;
for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
ranking[w] = b; points[w] = bScore; score[b] = -2;
}
p = malloc(nPlayers*34+1);
for(w=0; w<nPlayers && w<display; w++)
sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
free(names[0]);
return p;
}
void
Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
{ // count all piece types
int p, f, r;
*nB = *nW = *wStale = *bStale = *bishopColor = 0;
for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
p = board[r][f];
pCnt[p]++;
if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
p == BlackBishop || p == BlackFerz || p == BlackAlfil )
*bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
}
}
int
SufficientDefence (int pCnt[], int side, int nMine, int nHis)
{
int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
if(myPawns == 2 && nMine == 3) // KPP
return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
if(myPawns == 1 && nMine == 2) // KP
return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
if(myPawns) return FALSE;
if(pCnt[WhiteRook+side])
return pCnt[BlackRook-side] ||
pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
if(pCnt[WhiteCannon+side]) {
if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
return majorDefense || pCnt[BlackAlfil-side] >= 2;
}
if(pCnt[WhiteKnight+side])
return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
return FALSE;
}
int
MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
{
VariantClass v = gameInfo.variant;
if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
if(v == VariantShatranj) return TRUE; // always winnable through baring
if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
if(v == VariantXiangqi) {
int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
// if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
if(stale) // we have at least one last-rank P plus perhaps C
return majors // KPKX
|| pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
else // KCA*E*
return pCnt[WhiteFerz+side] // KCAK
|| pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
|| majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
// TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
} else if(v == VariantKnightmate) {
if(nMine == 1) return FALSE;
if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
} else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
if(nMine == 1) return FALSE; // bare King
if(nBishops && bisColor == 3) return TRUE; // There must be a second B/A/F, which can either block (his) or attack (mine) the escape square
nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
// by now we have King + 1 piece (or multiple Bishops on the same color)
if(pCnt[WhiteKnight+side])
return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
|| nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
if(nBishops)
return (pCnt[BlackKnight-side]); // KBKN, KFKN
if(pCnt[WhiteAlfil+side])
return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
if(pCnt[WhiteWazir+side])
return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
}
return TRUE;
}
int
CompareWithRights (Board b1, Board b2)
{
int rights = 0;
if(!CompareBoards(b1, b2)) return FALSE;
if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
/* compare castling rights */
if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
rights++; /* King lost rights, while rook still had them */
if( b1[CASTLING][2] != NoRights ) { /* king has rights */
if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
rights++; /* but at least one rook lost them */
}
if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
rights++;
if( b1[CASTLING][5] != NoRights ) {
if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
rights++;
}
return rights == 0;
}
int
Adjudicate (ChessProgramState *cps)
{ // [HGM] some adjudications useful with buggy engines
// [HGM] adjudicate: made into separate routine, which now can be called after every move
// In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
// Actually ending the game is now based on the additional internal condition canAdjudicate.
// Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
int k, drop, count = 0; static int bare = 1;
ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
Boolean canAdjudicate = !appData.icsActive;
// most tests only when we understand the game, i.e. legality-checking on
if( appData.testLegality )
{ /* [HGM] Some more adjudications for obstinate engines */
int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+2], i;
static int moveCount = 6;
ChessMove result;
char *reason = NULL;
/* Count what is on board. */
Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
/* Some material-based adjudications that have to be made before stalemate test */
if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
// [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
if(canAdjudicate && appData.checkMates) {
if(engineOpponent)
SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
"Xboard adjudication: King destroyed", GE_XBOARD );
return 1;
}
}
/* Bare King in Shatranj (loses) or Losers (wins) */
if( nrW == 1 || nrB == 1) {
if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
if(canAdjudicate && appData.checkMates) {
if(engineOpponent)
SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
"Xboard adjudication: Bare king", GE_XBOARD );
return 1;
}
} else
if( gameInfo.variant == VariantShatranj && --bare < 0)
{ /* bare King */
boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
if(canAdjudicate && appData.checkMates) {
/* but only adjudicate if adjudication enabled */
if(engineOpponent)
SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
"Xboard adjudication: Bare king", GE_XBOARD );
return 1;
}
}
} else bare = 1;
// don't wait for engine to announce game end if we can judge ourselves
switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
case MT_CHECK:
if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
checkCnt++;
if(checkCnt >= 2) {
reason = "Xboard adjudication: 3rd check";
boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
break;
}
}
}
case MT_NONE:
default:
break;
case MT_STEALMATE:
case MT_STALEMATE:
case MT_STAINMATE:
reason = "Xboard adjudication: Stalemate";
if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
else if(gameInfo.variant == VariantSuicide) // in suicide it depends
boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
EP_CHECKMATE : EP_WINS);
else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
}
break;
case MT_CHECKMATE:
reason = "Xboard adjudication: Checkmate";
boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
if(gameInfo.variant == VariantShogi) {
if(forwardMostMove > backwardMostMove
&& moveList[forwardMostMove-1][1] == '@'
&& CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
reason = "XBoard adjudication: pawn-drop mate";
boards[forwardMostMove][EP_STATUS] = EP_WINS;
}
}
break;
}
switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
case EP_STALEMATE:
result = GameIsDrawn; break;
case EP_CHECKMATE:
result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
case EP_WINS:
result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
default:
result = EndOfFile;
}
if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
if(engineOpponent)
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
GameEnds( result, reason, GE_XBOARD );
return 1;
}
/* Next absolutely insufficient mating material. */
if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
!MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
{ /* includes KBK, KNK, KK of KBKB with like Bishops */
/* always flag draws, for judging claims */
boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
if(canAdjudicate && appData.materialDraws) {
/* but only adjudicate them if adjudication enabled */
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
}
GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
return 1;
}
}
/* Then some trivial draws (only adjudicate, cannot be claimed) */
if(gameInfo.variant == VariantXiangqi ?
SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
: nrW + nrB == 4 &&
( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
|| nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
|| nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
|| nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
) ) {
if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
{ /* if the first 3 moves do not show a tactical win, declare draw */
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
}
GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
return 1;
}
} else moveCount = 6;
}
// Repetition draws and 50-move rule can be applied independently of legality testing
/* Check for rep-draws */
count = 0;
drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
&& gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
for(k = forwardMostMove-2;
k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
(signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
(signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
k-=2)
{ int rights=0;
if(CompareBoards(boards[k], boards[forwardMostMove])) {
/* compare castling rights */
if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
(boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
rights++; /* King lost rights, while rook still had them */
if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
rights++; /* but at least one rook lost them */
}
if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
(boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
rights++;
if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
rights++;
}
if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
&& appData.drawRepeats > 1) {
/* adjudicate after user-specified nr of repeats */
int result = GameIsDrawn;
char *details = "XBoard adjudication: repetition draw";
if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
// [HGM] xiangqi: check for forbidden perpetuals
int m, ourPerpetual = 1, hisPerpetual = 1;
for(m=forwardMostMove; m>k; m-=2) {
if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
ourPerpetual = 0; // the current mover did not always check
if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
hisPerpetual = 0; // the opponent did not always check
}
if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
ourPerpetual, hisPerpetual);
if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
details = "Xboard adjudication: perpetual checking";
} else
if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
break; // (or we would have caught him before). Abort repetition-checking loop.
} else
if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
result = BlackWins;
details = "Xboard adjudication: repetition";
}
} else // it must be XQ
// Now check for perpetual chases
if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
hisPerpetual = PerpetualChase(k, forwardMostMove);
ourPerpetual = PerpetualChase(k+1, forwardMostMove);
if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
static char resdet[MSG_SIZ];
result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
details = resdet;
snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
} else
if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
break; // Abort repetition-checking loop.
}
// if neither of us is checking or chasing all the time, or both are, it is draw
}
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
}
GameEnds( result, details, GE_XBOARD );
return 1;
}
if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
}
}
/* Now we test for 50-move draws. Determine ply count */
count = forwardMostMove;
/* look for last irreversble move */
while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
count--;
/* if we hit starting position, add initial plies */
if( count == backwardMostMove )
count -= initialRulePlies;
count = forwardMostMove - count;
if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
// adjust reversible move counter for checks in Xiangqi
int i = forwardMostMove - count, inCheck = 0, lastCheck;
if(i < backwardMostMove) i = backwardMostMove;
while(i <= forwardMostMove) {
lastCheck = inCheck; // check evasion does not count
inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
if(inCheck || lastCheck) count--; // check does not count
i++;
}
}
if( count >= 100)
boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
/* this is used to judge if draw claims are legal */
if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
}
GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
return 1;
}
/* if draw offer is pending, treat it as a draw claim
* when draw condition present, to allow engines a way to
* claim draws before making their move to avoid a race
* condition occurring after their move
*/
if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
char *p = NULL;
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
p = "Draw claim: 50-move rule";
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
p = "Draw claim: 3-fold repetition";
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
p = "Draw claim: insufficient mating material";
if( p != NULL && canAdjudicate) {
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
}
GameEnds( GameIsDrawn, p, GE_XBOARD );
return 1;
}
}
if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
if(engineOpponent) {
SendToProgram("force\n", engineOpponent); // suppress reply
SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
}
GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
return 1;
}
return 0;
}
typedef int (CDECL *PPROBE_EGBB) (int player, int *piece, int *square);
typedef int (CDECL *PLOAD_EGBB) (char *path, int cache_size, int load_options);
static int egbbCode[] = { 6, 5, 4, 3, 2, 1 };
static int
BitbaseProbe ()
{
int pieces[10], squares[10], cnt=0, r, f, res;
static int loaded;
static PPROBE_EGBB probeBB;
if(!appData.testLegality) return 10;
if(BOARD_HEIGHT != 8 || BOARD_RGHT-BOARD_LEFT != 8) return 12;
if(gameInfo.holdingsSize && gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess) return 12;
if(loaded == 2 && forwardMostMove < 2) loaded = 0; // retry on new game
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
ChessSquare piece = boards[forwardMostMove][r][f];
int black = (piece >= BlackPawn);
int type = piece - black*BlackPawn;
if(piece == EmptySquare) continue;
if(type != WhiteKing && type > WhiteQueen) return 12; // unorthodox piece
if(type == WhiteKing) type = WhiteQueen + 1;
type = egbbCode[type];
squares[cnt] = r*(BOARD_RGHT - BOARD_LEFT) + f - BOARD_LEFT;
pieces[cnt] = type + black*6;
if(++cnt > 5) return 11;
}
pieces[cnt] = squares[cnt] = 0;
// probe EGBB
if(loaded == 2) return 13; // loading failed before
if(loaded == 0) {
char *p, *path = strstr(appData.egtFormats, "scorpio:"), buf[MSG_SIZ];
HMODULE lib;
PLOAD_EGBB loadBB;
loaded = 2; // prepare for failure
if(!path) return 13; // no egbb installed
strncpy(buf, path + 8, MSG_SIZ);
if(p = strchr(buf, ',')) *p = NULLCHAR; else p = buf + strlen(buf);
snprintf(p, MSG_SIZ - strlen(buf), "%c%s", SLASH, EGBB_NAME);
lib = LoadLibrary(buf);
if(!lib) { DisplayError(_("could not load EGBB library"), 0); return 13; }
loadBB = (PLOAD_EGBB) GetProcAddress(lib, "load_egbb_xmen");
probeBB = (PPROBE_EGBB) GetProcAddress(lib, "probe_egbb_xmen");
if(!loadBB || !probeBB) { DisplayError(_("wrong EGBB version"), 0); return 13; }
p[1] = NULLCHAR; loadBB(buf, 64*1028, 2); // 2 = SMART_LOAD
loaded = 1; // success!
}
res = probeBB(forwardMostMove & 1, pieces, squares);
return res > 0 ? 1 : res < 0 ? -1 : 0;
}
char *
SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
{ // [HGM] book: this routine intercepts moves to simulate book replies
char *bookHit = NULL;
if(cps->drawDepth && BitbaseProbe() == 0) { // [HG} egbb: reduce depth in drawn position
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "sd %d\n", cps->drawDepth);
SendToProgram(buf, cps);
}
//first determine if the incoming move brings opponent into his book
if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
if(bookHit != NULL && !cps->bookSuspend) {
// make sure opponent is not going to reply after receiving move to book position
SendToProgram("force\n", cps);
cps->bookSuspend = TRUE; // flag indicating it has to be restarted
}
if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
// now arrange restart after book miss
if(bookHit) {
// after a book hit we never send 'go', and the code after the call to this routine
// has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
char buf[MSG_SIZ], *move = bookHit;
if(cps->useSAN) {
int fromX, fromY, toX, toY;
char promoChar;
ChessMove moveType;
move = buf + 30;
if (ParseOneMove(bookHit, forwardMostMove, &moveType,
&fromX, &fromY, &toX, &toY, &promoChar)) {
(void) CoordsToAlgebraic(boards[forwardMostMove],
PosFlags(forwardMostMove),
fromY, fromX, toY, toX, promoChar, move);
} else {
if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
bookHit = NULL;
}
}
snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
SendToProgram(buf, cps);
if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
} else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
SendToProgram("go\n", cps);
cps->bookSuspend = FALSE; // after a 'go' we are never suspended
} else { // 'go' might be sent based on 'firstMove' after this routine returns
if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
SendToProgram("go\n", cps);
cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
}
return bookHit; // notify caller of hit, so it can take action to send move to opponent
}
int
LoadError (char *errmess, ChessProgramState *cps)
{ // unloads engine and switches back to -ncp mode if it was first
if(cps->initDone) return FALSE;
cps->isr = NULL; // this should suppress further error popups from breaking pipes
DestroyChildProcess(cps->pr, 9 ); // just to be sure
cps->pr = NoProc;
if(cps == &first) {
appData.noChessProgram = TRUE;
gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
gameMode = BeginningOfGame; ModeHighlight();
SetNCPMode();
}
if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
DisplayMessage("", ""); // erase waiting message
if(errmess) DisplayError(errmess, 0); // announce reason, if given
return TRUE;
}
char *savedMessage;
ChessProgramState *savedState;
void
DeferredBookMove (void)
{
if(savedState->lastPing != savedState->lastPong)
ScheduleDelayedEvent(DeferredBookMove, 10);
else
HandleMachineMove(savedMessage, savedState);
}
static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
static ChessProgramState *stalledEngine;
static char stashedInputMove[MSG_SIZ], abortEngineThink;
void
HandleMachineMove (char *message, ChessProgramState *cps)
{
static char firstLeg[20], legs;
char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
char realname[MSG_SIZ];
int fromX, fromY, toX, toY;
ChessMove moveType;
char promoChar, roar;
char *p, *pv=buf1;
int oldError;
char *bookHit;
if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
// [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
DisplayError(_("Invalid pairing from pairing engine"), 0);
return;
}
pairingReceived = 1;
NextMatchGame();
return; // Skim the pairing messages here.
}
oldError = cps->userError; cps->userError = 0;
FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
/*
* Kludge to ignore BEL characters
*/
while (*message == '\007') message++;
/*
* [HGM] engine debug message: ignore lines starting with '#' character
*/
if(cps->debug && *message == '#') return;
/*
* Look for book output
*/
if (cps == &first && bookRequested) {
if (message[0] == '\t' || message[0] == ' ') {
/* Part of the book output is here; append it */
strcat(bookOutput, message);
strcat(bookOutput, " \n");
return;
} else if (bookOutput[0] != NULLCHAR) {
/* All of book output has arrived; display it */
char *p = bookOutput;
while (*p != NULLCHAR) {
if (*p == '\t') *p = ' ';
p++;
}
DisplayInformation(bookOutput);
bookRequested = FALSE;
/* Fall through to parse the current output */
}
}
/*
* Look for machine move.
*/
if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
(sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
{
if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
safeStrCpy(stashedInputMove, message, MSG_SIZ);
stalledEngine = cps;
if(appData.ponderNextMove) { // bring opponent out of ponder
if(gameMode == TwoMachinesPlay) {
if(cps->other->pause)
PauseEngine(cps->other);
else
SendToProgram("easy\n", cps->other);
}
}
StopClocks();
return;
}
if(cps->usePing) {
/* This method is only useful on engines that support ping */
if(abortEngineThink) {
if (appData.debugMode) {
fprintf(debugFP, "Undoing move from aborted think of %s\n", cps->which);
}
SendToProgram("undo\n", cps);
return;
}
if (cps->lastPing != cps->lastPong) {
/* Extra move from before last new; ignore */
if (appData.debugMode) {
fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
}
return;
}
} else {
int machineWhite = FALSE;
switch (gameMode) {
case BeginningOfGame:
/* Extra move from before last reset; ignore */
if (appData.debugMode) {
fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
}
return;
case EndOfGame:
case IcsIdle:
default:
/* Extra move after we tried to stop. The mode test is
not a reliable way of detecting this problem, but it's
the best we can do on engines that don't support ping.
*/
if (appData.debugMode) {
fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
cps->which, gameMode);
}
SendToProgram("undo\n", cps);
return;
case MachinePlaysWhite:
case IcsPlayingWhite:
machineWhite = TRUE;
break;
case MachinePlaysBlack:
case IcsPlayingBlack:
machineWhite = FALSE;
break;
case TwoMachinesPlay:
machineWhite = (cps->twoMachinesColor[0] == 'w');
break;
}
if (WhiteOnMove(forwardMostMove) != machineWhite) {
if (appData.debugMode) {
fprintf(debugFP,
"Ignoring move out of turn by %s, gameMode %d"
", forwardMost %d\n",
cps->which, gameMode, forwardMostMove);
}
return;
}
}
if(cps->alphaRank) AlphaRank(machineMove, 4);
// [HGM] lion: (some very limited) support for Alien protocol
killX = killY = kill2X = kill2Y = -1;
if(machineMove[strlen(machineMove)-1] == ',') { // move ends in coma: non-final leg of composite move
if(legs++) return; // middle leg contains only redundant info, ignore (but count it)
safeStrCpy(firstLeg, machineMove, 20); // just remember it for processing when second leg arrives
return;
}
if(p = strchr(machineMove, ',')) { // we got both legs in one (happens on book move)
char *q = strchr(p+1, ','); // second comma?
safeStrCpy(firstLeg, machineMove, 20); // kludge: fake we received the first leg earlier, and clip it off
if(q) legs = 2, p = q; else legs = 1; // with 3-leg move we clipof first two legs!
safeStrCpy(machineMove, firstLeg + (p - machineMove) + 1, 20);
}
if(firstLeg[0]) { // there was a previous leg;
// only support case where same piece makes two step
char buf[20], *p = machineMove+1, *q = buf+1, f;
safeStrCpy(buf, machineMove, 20);
while(isdigit(*q)) q++; // find start of to-square
safeStrCpy(machineMove, firstLeg, 20);
while(isdigit(*p)) p++; // to-square of first leg (which is now copied to machineMove)
if(legs == 2) sscanf(p, "%c%d", &f, &kill2Y), kill2X = f - AAA, kill2Y -= ONE - '0'; // in 3-leg move 2nd kill is to-sqr of 1st leg
else if(*p == *buf) // if first-leg to not equal to second-leg from first leg says unmodified (assume it is King move of castling)
safeStrCpy(p, q, 20); // glue to-square of second leg to from-square of first, to process over-all move
sscanf(buf, "%c%d", &f, &killY); killX = f - AAA; killY -= ONE - '0'; // pass intermediate square to MakeMove in global
firstLeg[0] = NULLCHAR; legs = 0;
}
if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
&fromX, &fromY, &toX, &toY, &promoChar)) {
/* Machine move could not be parsed; ignore it. */
snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
machineMove, _(cps->which));
DisplayMoveError(buf1);
snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c via %c%c, %c%c) res=%d",
machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, killX+AAA, killY+ONE, kill2X+AAA, kill2Y+ONE, moveType);
if (gameMode == TwoMachinesPlay) {
GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
buf1, GE_XBOARD);
}
return;
}
/* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
/* So we have to redo legality test with true e.p. status here, */
/* to make sure an illegal e.p. capture does not slip through, */
/* to cause a forfeit on a justified illegal-move complaint */
/* of the opponent. */
if( gameMode==TwoMachinesPlay && appData.testLegality ) {
ChessMove moveType;
moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
fromY, fromX, toY, toX, promoChar);
if(moveType == IllegalMove) {
snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
buf1, GE_XBOARD);
return;
} else if(!appData.fischerCastling)
/* [HGM] Kludge to handle engines that send FRC-style castling
when they shouldn't (like TSCP-Gothic) */
switch(moveType) {
case WhiteASideCastleFR:
case BlackASideCastleFR:
toX+=2;
currentMoveString[2]++;
break;
case WhiteHSideCastleFR:
case BlackHSideCastleFR:
toX--;
currentMoveString[2]--;
break;
default: ; // nothing to do, but suppresses warning of pedantic compilers
}
}
hintRequested = FALSE;
lastHint[0] = NULLCHAR;
bookRequested = FALSE;
/* Program may be pondering now */
cps->maybeThinking = TRUE;
if (cps->sendTime == 2) cps->sendTime = 1;
if (cps->offeredDraw) cps->offeredDraw--;
/* [AS] Save move info*/
pvInfoList[ forwardMostMove ].score = programStats.score;
pvInfoList[ forwardMostMove ].depth = programStats.depth;
pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
/* Test suites abort the 'game' after one move */
if(*appData.finger) {
static FILE *f;
char *fen = PositionToFEN(backwardMostMove, NULL, 0); // no counts in EPD
if(!f) f = fopen(appData.finger, "w");
if(f) fprintf(f, "%s bm %s;\n", fen, parseList[backwardMostMove]), fflush(f);
else { DisplayFatalError("Bad output file", errno, 0); return; }
free(fen);
GameEnds(GameUnfinished, NULL, GE_XBOARD);
}
if(appData.epd) {
if(solvingTime >= 0) {
snprintf(buf1, MSG_SIZ, "%d. %4.2fs: %s ", matchGame, solvingTime/100., parseList[backwardMostMove]);
totalTime += solvingTime; first.matchWins++; solvingTime = -1;
} else {
snprintf(buf1, MSG_SIZ, "%d. %s?%s ", matchGame, parseList[backwardMostMove], solvingTime == -2 ? " ???" : "");
if(solvingTime == -2) second.matchWins++;
}
OutputKibitz(2, buf1);
GameEnds(GameUnfinished, NULL, GE_XBOARD);
}
/* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
if( gameMode == TwoMachinesPlay && appData.adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
int count = 0;
while( count < adjudicateLossPlies ) {
int score = pvInfoList[ forwardMostMove - count - 1 ].score;
if( count & 1 ) {
score = -score; /* Flip score for winning side */
}
if( score > appData.adjudicateLossThreshold ) {
break;
}
count++;
}
if( count >= adjudicateLossPlies ) {
ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
"Xboard adjudication",
GE_XBOARD );
return;
}
}
if(Adjudicate(cps)) {
ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
return; // [HGM] adjudicate: for all automatic game ends
}
#if ZIPPY
if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
first.initDone) {
if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
SendToICS("draw ");
SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
}
SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
ics_user_moved = 1;
if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
char buf[3*MSG_SIZ];
snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
programStats.score / 100.,
programStats.depth,
programStats.time / 100.,
(unsigned int)programStats.nodes,
(unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
programStats.movelist);
SendToICS(buf);
}
}
#endif
/* [AS] Clear stats for next move */
ClearProgramStats();
thinkOutput[0] = NULLCHAR;
hiddenThinkOutputState = 0;
bookHit = NULL;
if (gameMode == TwoMachinesPlay) {
/* [HGM] relaying draw offers moved to after reception of move */
/* and interpreting offer as claim if it brings draw condition */
if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
SendToProgram("draw\n", cps->other);
}
if (cps->other->sendTime) {
SendTimeRemaining(cps->other,
cps->other->twoMachinesColor[0] == 'w');
}
bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
if (firstMove && !bookHit) {
firstMove = FALSE;
if (cps->other->useColors) {
SendToProgram(cps->other->twoMachinesColor, cps->other);
}
SendToProgram("go\n", cps->other);
}
cps->other->maybeThinking = TRUE;
}
roar = (killX >= 0 && IS_LION(boards[forwardMostMove][toY][toX]));
ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
if (!pausing && appData.ringBellAfterMoves) {
if(!roar) RingBell();
}
/*
* Reenable menu items that were disabled while
* machine was thinking
*/
if (gameMode != TwoMachinesPlay)
SetUserThinkingEnables();
// [HGM] book: after book hit opponent has received move and is now in force mode
// force the book reply into it, and then fake that it outputted this move by jumping
// back to the beginning of HandleMachineMove, with cps toggled and message set to this move
if(bookHit) {
static char bookMove[MSG_SIZ]; // a bit generous?
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
message = bookMove;
cps = cps->other;
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
if(cps->lastPing != cps->lastPong) {
savedMessage = message; // args for deferred call
savedState = cps;
ScheduleDelayedEvent(DeferredBookMove, 10);
return;
}
goto FakeBookMove;
}
return;
}
/* Set special modes for chess engines. Later something general
* could be added here; for now there is just one kludge feature,
* needed because Crafty 15.10 and earlier don't ignore SIGINT
* when "xboard" is given as an interactive command.
*/
if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
cps->useSigint = FALSE;
cps->useSigterm = FALSE;
}
if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
ParseFeatures(message+8, cps);
return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
}
if (!strncmp(message, "setup ", 6) &&
(!appData.testLegality || gameInfo.variant == VariantFairy || gameInfo.variant == VariantUnknown ||
NonStandardBoardSize(gameInfo.variant, gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize))
) { // [HGM] allow first engine to define opening position
int dummy, w, h, hand, s=6; char buf[MSG_SIZ], varName[MSG_SIZ];
if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
*buf = NULLCHAR;
if(sscanf(message, "setup (%s", buf) == 1) {
s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTableEsc(pieceToChar, buf, SUFFIXES);
ASSIGN(appData.pieceToCharTable, buf);
}
dummy = sscanf(message+s, "%dx%d+%d_%s", &w, &h, &hand, varName);
if(dummy >= 3) {
while(message[s] && message[s++] != ' ');
if(BOARD_HEIGHT != h || BOARD_WIDTH != w + 4*(hand != 0) || gameInfo.holdingsSize != hand ||
dummy == 4 && gameInfo.variant != StringToVariant(varName) ) { // engine wants to change board format or variant
if(hand <= h) deadRanks = 0; else deadRanks = hand - h, h = hand; // adapt board to over-sized holdings
appData.NrFiles = w; appData.NrRanks = h; appData.holdingsSize = hand;
if(dummy == 4) gameInfo.variant = StringToVariant(varName); // parent variant
InitPosition(1); // calls InitDrawingSizes to let new parameters take effect
if(*buf) SetCharTableEsc(pieceToChar, buf, SUFFIXES); // do again, for it was spoiled by InitPosition
startedFromSetupPosition = FALSE;
}
}
if(startedFromSetupPosition) return;
ParseFEN(boards[0], &dummy, message+s, FALSE);
DrawPosition(TRUE, boards[0]);
CopyBoard(initialPosition, boards[0]);
startedFromSetupPosition = TRUE;
return;
}
if(sscanf(message, "piece %s %s", buf2, buf1) == 2) {
ChessSquare piece = WhitePawn;
char *p=message+6, *q, *s = SUFFIXES, ID = *p, promoted = 0;
if(*p == '+') promoted++, ID = *++p;
if(q = strchr(s, p[1])) ID += 64*(q - s + 1), p++;
piece = CharToPiece(ID & 255); if(promoted) piece = CHUPROMOTED(piece);
if(cps != &first || appData.testLegality && *engineVariant == NULLCHAR
/* always accept definition of */ && piece != WhiteFalcon && piece != BlackFalcon
/* wild-card pieces. */ && piece != WhiteCobra && piece != BlackCobra
/* For variants we don't have */ && gameInfo.variant != VariantBerolina
/* correct rules for, we cannot */ && gameInfo.variant != VariantCylinder
/* enforce legality on our own! */ && gameInfo.variant != VariantUnknown
&& gameInfo.variant != VariantGreat
&& gameInfo.variant != VariantFairy ) return;
if(piece < EmptySquare) {
pieceDefs = TRUE;
ASSIGN(pieceDesc[piece], buf1);
if((ID & 32) == 0 && p[1] == '&') { ASSIGN(pieceDesc[WHITE_TO_BLACK piece], buf1); }
}
return;
}
if(!appData.testLegality && sscanf(message, "choice %s", promoRestrict) == 1) {
if(deferChoice) {
LeftClick(Press, 0, 0); // finish the click that was interrupted
} else if(promoSweep != EmptySquare) {
promoSweep = CharToPiece(currentMove&1 ? ToLower(*promoRestrict) : ToUpper(*promoRestrict));
if(strlen(promoRestrict) > 1) Sweep(0);
}
return;
}
/* [HGM] Allow engine to set up a position. Don't ask me why one would
* want this, I was asked to put it in, and obliged.
*/
if (!strncmp(message, "setboard ", 9)) {
Board initial_position;
GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9, FALSE)) {
DisplayError(_("Bad FEN received from engine"), 0);
return ;
} else {
Reset(TRUE, FALSE);
CopyBoard(boards[0], initial_position);
initialRulePlies = FENrulePlies;
if(blackPlaysFirst) gameMode = MachinePlaysWhite;
else gameMode = MachinePlaysBlack;
DrawPosition(FALSE, boards[currentMove]);
}
return;
}
/*
* Look for communication commands
*/
if (!strncmp(message, "telluser ", 9)) {
if(message[9] == '\\' && message[10] == '\\')
EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
PlayTellSound();
DisplayNote(message + 9);
return;
}
if (!strncmp(message, "tellusererror ", 14)) {
cps->userError = 1;
if(message[14] == '\\' && message[15] == '\\')
EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
PlayTellSound();
DisplayError(message + 14, 0);
return;
}
if (!strncmp(message, "tellopponent ", 13)) {
if (appData.icsActive) {
if (loggedOn) {
snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
SendToICS(buf1);
}
} else {
DisplayNote(message + 13);
}
return;
}
if (!strncmp(message, "tellothers ", 11)) {
if (appData.icsActive) {
if (loggedOn) {
snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
SendToICS(buf1);
}
} else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
return;
}
if (!strncmp(message, "tellall ", 8)) {
if (appData.icsActive) {
if (loggedOn) {
snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
SendToICS(buf1);
}
} else {
DisplayNote(message + 8);
}
return;
}
if (strncmp(message, "warning", 7) == 0) {
/* Undocumented feature, use tellusererror in new code */
DisplayError(message, 0);
return;
}
if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
strcat(realname, " query");
AskQuestion(realname, buf2, buf1, cps->pr);
return;
}
/* Commands from the engine directly to ICS. We don't allow these to be
* sent until we are logged on. Crafty kibitzes have been known to
* interfere with the login process.
*/
if (loggedOn) {
if (!strncmp(message, "tellics ", 8)) {
SendToICS(message + 8);
SendToICS("\n");
return;
}
if (!strncmp(message, "tellicsnoalias ", 15)) {
SendToICS(ics_prefix);
SendToICS(message + 15);
SendToICS("\n");
return;
}
/* The following are for backward compatibility only */
if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
!strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
SendToICS(ics_prefix);
SendToICS(message);
SendToICS("\n");
return;
}
}
if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
if(initPing == cps->lastPong) {
if(gameInfo.variant == VariantUnknown) {
DisplayError(_("Engine did not send setup for non-standard variant"), 0);
*engineVariant = NULLCHAR; ASSIGN(appData.variant, "normal"); // back to normal as error recovery?
GameEnds(GameUnfinished, NULL, GE_XBOARD);
}
initPing = -1;
}
if(cps->lastPing == cps->lastPong && abortEngineThink) {
abortEngineThink = FALSE;
DisplayMessage("", "");
ThawUI();
}
return;
}
if(!strncmp(message, "highlight ", 10)) {
if(appData.testLegality && !*engineVariant && appData.markers) return;
MarkByFEN(message+10); // [HGM] alien: allow engine to mark board squares
return;
}
if(!strncmp(message, "click ", 6)) {
char f, c=0; int x, y; // [HGM] alien: allow engine to finish user moves (i.e. engine-driven one-click moving)
if(appData.testLegality || !appData.oneClick) return;
sscanf(message+6, "%c%d%c", &f, &y, &c);
x = f - 'a' + BOARD_LEFT, y -= ONE - '0';
if(flipView) x = BOARD_WIDTH-1 - x; else y = BOARD_HEIGHT-1 - y;
x = x*squareSize + (x+1)*lineGap + squareSize/2;
y = y*squareSize + (y+1)*lineGap + squareSize/2;
f = first.highlight; first.highlight = 0; // kludge to suppress lift/put in response to own clicks
if(lastClickType == Press) // if button still down, fake release on same square, to be ready for next click
LeftClick(Release, lastLeftX, lastLeftY);
controlKey = (c == ',');
LeftClick(Press, x, y);
LeftClick(Release, x, y);
first.highlight = f;
return;
}
/*
* If the move is illegal, cancel it and redraw the board.
* Also deal with other error cases. Matching is rather loose
* here to accommodate engines written before the spec.
*/
if (strncmp(message + 1, "llegal move", 11) == 0 ||
strncmp(message, "Error", 5) == 0) {
if (StrStr(message, "name") ||
StrStr(message, "rating") || StrStr(message, "?") ||
StrStr(message, "result") || StrStr(message, "board") ||
StrStr(message, "bk") || StrStr(message, "computer") ||
StrStr(message, "variant") || StrStr(message, "hint") ||
StrStr(message, "random") || StrStr(message, "depth") ||
StrStr(message, "accepted")) {
return;
}
if (StrStr(message, "protover")) {
/* Program is responding to input, so it's apparently done
initializing, and this error message indicates it is
protocol version 1. So we don't need to wait any longer
for it to initialize and send feature commands. */
FeatureDone(cps, 1);
cps->protocolVersion = 1;
return;
}
cps->maybeThinking = FALSE;
if (StrStr(message, "draw")) {
/* Program doesn't have "draw" command */
cps->sendDrawOffers = 0;
return;
}
if (cps->sendTime != 1 &&
(StrStr(message, "time") || StrStr(message, "otim"))) {
/* Program apparently doesn't have "time" or "otim" command */
cps->sendTime = 0;
return;
}
if (StrStr(message, "analyze")) {
cps->analysisSupport = FALSE;
cps->analyzing = FALSE;
// Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
EditGameEvent(); // [HGM] try to preserve loaded game
snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
DisplayError(buf2, 0);
return;
}
if (StrStr(message, "(no matching move)st")) {
/* Special kludge for GNU Chess 4 only */
cps->stKludge = TRUE;
SendTimeControl(cps, movesPerSession, timeControl,
timeIncrement, appData.searchDepth,
searchTime);
return;
}
if (StrStr(message, "(no matching move)sd")) {
/* Special kludge for GNU Chess 4 only */
cps->sdKludge = TRUE;
SendTimeControl(cps, movesPerSession, timeControl,
timeIncrement, appData.searchDepth,
searchTime);
return;
}
if (!StrStr(message, "llegal")) {
return;
}
if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
gameMode == IcsIdle) return;
if (forwardMostMove <= backwardMostMove) return;
if (pausing) PauseEvent();
if(appData.forceIllegal) {
// [HGM] illegal: machine refused move; force position after move into it
SendToProgram("force\n", cps);
if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
// we have a real problem now, as SendBoard will use the a2a3 kludge
// when black is to move, while there might be nothing on a2 or black
// might already have the move. So send the board as if white has the move.
// But first we must change the stm of the engine, as it refused the last move
SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
if(WhiteOnMove(forwardMostMove)) {
SendToProgram("a7a6\n", cps); // for the engine black still had the move
SendBoard(cps, forwardMostMove); // kludgeless board
} else {
SendToProgram("a2a3\n", cps); // for the engine white still had the move
CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
SendBoard(cps, forwardMostMove+1); // kludgeless board
}
} else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay)
SendToProgram("go\n", cps);
return;
} else
if (gameMode == PlayFromGameFile) {
/* Stop reading this game file */
gameMode = EditGame;
ModeHighlight();
}
/* [HGM] illegal-move claim should forfeit game when Xboard */
/* only passes fully legal moves */
if( appData.testLegality && gameMode == TwoMachinesPlay ) {
GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
"False illegal-move claim", GE_XBOARD );
return; // do not take back move we tested as valid
}
currentMove = forwardMostMove-1;
DisplayMove(currentMove-1); /* before DisplayMoveError */
SwitchClocks(forwardMostMove-1); // [HGM] race
DisplayBothClocks();
snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
parseList[currentMove], _(cps->which));
DisplayMoveError(buf1);
DrawPosition(FALSE, boards[currentMove]);
SetUserThinkingEnables();
return;
}
if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
/* Program has a broken "time" command that
outputs a string not ending in newline.
Don't use it. */
cps->sendTime = 0;
}
if (cps->pseudo) { // [HGM] pseudo-engine, granted unusual powers
if (sscanf(message, "wtime %ld\n", &whiteTimeRemaining) == 1 || // adjust clock times
sscanf(message, "btime %ld\n", &blackTimeRemaining) == 1 ) return;
}
/*
* If chess program startup fails, exit with an error message.
* Attempts to recover here are futile. [HGM] Well, we try anyway
*/
if ((StrStr(message, "unknown host") != NULL)
|| (StrStr(message, "No remote directory") != NULL)
|| (StrStr(message, "not found") != NULL)
|| (StrStr(message, "No such file") != NULL)
|| (StrStr(message, "can't alloc") != NULL)
|| (StrStr(message, "Permission denied") != NULL)) {
cps->maybeThinking = FALSE;
snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
_(cps->which), cps->program, cps->host, message);
RemoveInputSource(cps->isr);
if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
}
return;
}
/*
* Look for hint output
*/
if (sscanf(message, "Hint: %s", buf1) == 1) {
if (cps == &first && hintRequested) {
hintRequested = FALSE;
if (ParseOneMove(buf1, forwardMostMove, &moveType,
&fromX, &fromY, &toX, &toY, &promoChar)) {
(void) CoordsToAlgebraic(boards[forwardMostMove],
PosFlags(forwardMostMove),
fromY, fromX, toY, toX, promoChar, buf1);
snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
DisplayInformation(buf2);
} else {
/* Hint move could not be parsed!? */
snprintf(buf2, sizeof(buf2),
_("Illegal hint move \"%s\"\nfrom %s chess program"),
buf1, _(cps->which));
DisplayError(buf2, 0);
}
} else {
safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
}
return;
}
/*
* Ignore other messages if game is not in progress
*/
if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
/*
* look for win, lose, draw, or draw offer
*/
if (strncmp(message, "1-0", 3) == 0) {
char *p, *q, *r = "";
p = strchr(message, '{');
if (p) {
q = strchr(p, '}');
if (q) {
*q = NULLCHAR;
r = p + 1;
}
}
GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
return;
} else if (strncmp(message, "0-1", 3) == 0) {
char *p, *q, *r = "";
p = strchr(message, '{');
if (p) {
q = strchr(p, '}');
if (q) {
*q = NULLCHAR;
r = p + 1;
}
}
/* Kludge for Arasan 4.1 bug */
if (strcmp(r, "Black resigns") == 0) {
GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
return;
}
GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
return;
} else if (strncmp(message, "1/2", 3) == 0) {
char *p, *q, *r = "";
p = strchr(message, '{');
if (p) {
q = strchr(p, '}');
if (q) {
*q = NULLCHAR;
r = p + 1;
}
}
GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
return;
} else if (strncmp(message, "White resign", 12) == 0) {
GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
return;
} else if (strncmp(message, "Black resign", 12) == 0) {
GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
return;
} else if (strncmp(message, "White matches", 13) == 0 ||
strncmp(message, "Black matches", 13) == 0 ) {
/* [HGM] ignore GNUShogi noises */
return;
} else if (strncmp(message, "White", 5) == 0 &&
message[5] != '(' &&
StrStr(message, "Black") == NULL) {
GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
return;
} else if (strncmp(message, "Black", 5) == 0 &&
message[5] != '(') {
GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
return;
} else if (strcmp(message, "resign") == 0 ||
strcmp(message, "computer resigns") == 0) {
switch (gameMode) {
case MachinePlaysBlack:
case IcsPlayingBlack:
GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
break;
case MachinePlaysWhite:
case IcsPlayingWhite:
GameEnds(BlackWins, "White resigns", GE_ENGINE);
break;
case TwoMachinesPlay:
if (cps->twoMachinesColor[0] == 'w')
GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
else
GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
break;
default:
/* can't happen */
break;
}
return;
} else if (strncmp(message, "opponent mates", 14) == 0) {
switch (gameMode) {
case MachinePlaysBlack:
case IcsPlayingBlack:
GameEnds(WhiteWins, "White mates", GE_ENGINE);
break;
case MachinePlaysWhite:
case IcsPlayingWhite:
GameEnds(BlackWins, "Black mates", GE_ENGINE);
break;
case TwoMachinesPlay:
if (cps->twoMachinesColor[0] == 'w')
GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
else
GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
break;
default:
/* can't happen */
break;
}
return;
} else if (strncmp(message, "computer mates", 14) == 0) {
switch (gameMode) {
case MachinePlaysBlack:
case IcsPlayingBlack:
GameEnds(BlackWins, "Black mates", GE_ENGINE1);
break;
case MachinePlaysWhite:
case IcsPlayingWhite:
GameEnds(WhiteWins, "White mates", GE_ENGINE);
break;
case TwoMachinesPlay:
if (cps->twoMachinesColor[0] == 'w')
GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
else
GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
break;
default:
/* can't happen */
break;
}
return;
} else if (strncmp(message, "checkmate", 9) == 0) {
if (WhiteOnMove(forwardMostMove)) {
GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
} else {
GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
}
return;
} else if (strstr(message, "Draw") != NULL ||
strstr(message, "game is a draw") != NULL) {
GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
return;
} else if (strstr(message, "offer") != NULL &&
strstr(message, "draw") != NULL) {
#if ZIPPY
if (appData.zippyPlay && first.initDone) {
/* Relay offer to ICS */
SendToICS(ics_prefix);
SendToICS("draw\n");
}
#endif
cps->offeredDraw = 2; /* valid until this engine moves twice */
if (gameMode == TwoMachinesPlay) {
if (cps->other->offeredDraw) {
GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
/* [HGM] in two-machine mode we delay relaying draw offer */
/* until after we also have move, to see if it is really claim */
}
} else if (gameMode == MachinePlaysWhite ||
gameMode == MachinePlaysBlack) {
if (userOfferedDraw) {
DisplayInformation(_("Machine accepts your draw offer"));
GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
} else {
DisplayInformation(_("Machine offers a draw.\nSelect Action / Draw to accept."));
}
}
}
/*
* Look for thinking output
*/
if ( appData.showThinking // [HGM] thinking: test all options that cause this output
|| !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
) {
int plylev, mvleft, mvtot, curscore, time;
char mvname[MOVE_LEN];
u64 nodes; // [DM]
char plyext;
int ignore = FALSE;
int prefixHint = FALSE;
mvname[0] = NULLCHAR;
switch (gameMode) {
case MachinePlaysBlack:
case IcsPlayingBlack:
if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
break;
case MachinePlaysWhite:
case IcsPlayingWhite:
if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
break;
case AnalyzeMode:
case AnalyzeFile:
break;
case IcsObserving: /* [DM] icsEngineAnalyze */
if (!appData.icsEngineAnalyze) ignore = TRUE;
break;
case TwoMachinesPlay:
if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
ignore = TRUE;
}
break;
default:
ignore = TRUE;
break;
}
if (!ignore) {
ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
int solved = 0;
buf1[0] = NULLCHAR;
if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
&plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
char score_buf[MSG_SIZ];
if(nodes>>32 == u64Const(0xFFFFFFFF)) // [HGM] negative node count read
nodes += u64Const(0x100000000);
if (plyext != ' ' && plyext != '\t') {
time *= 100;
}
/* [AS] Negate score if machine is playing black and reporting absolute scores */
if( cps->scoreIsAbsolute &&
( gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
(gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
!WhiteOnMove(currentMove)
) )
{
curscore = -curscore;
}
if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
if(*bestMove) { // rememer time best EPD move was first found
int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
ChessMove mt; char *p = bestMove;
int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
solved = 0;
while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
solvingTime = (solvingTime < 0 ? time : solvingTime);
solved = 1;
break;
}
while(*p && *p != ' ') p++;
while(*p == ' ') p++;
}
if(!solved) solvingTime = -1;
}
if(*avoidMove && !solved) {
int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
ChessMove mt; char *p = avoidMove, solved = 1;
int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
solved = 0; solvingTime = -2;
break;
}
while(*p && *p != ' ') p++;
while(*p == ' ') p++;
}
if(solved && !*bestMove) solvingTime = (solvingTime < 0 ? time : solvingTime);
}
if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
char buf[MSG_SIZ];
FILE *f;
snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
if(f = fopen(buf, "w")) { // export PV to applicable PV file
fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
fclose(f);
}
else
/* TRANSLATORS: PV = principal variation, the variation the chess engine thinks is the best for everyone */
DisplayError(_("failed writing PV"), 0);
}
tempStats.depth = plylev;
tempStats.nodes = nodes;
tempStats.time = time;
tempStats.score = curscore;
tempStats.got_only_move = 0;
if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
int ticklen;
if(cps->nps == 0) ticklen = 10*time; // use engine reported time
else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
}
/* Buffer overflow protection */
if (pv[0] != NULLCHAR) {
if (strlen(pv) >= sizeof(tempStats.movelist)
&& appData.debugMode) {
fprintf(debugFP,
"PV is too long; using the first %u bytes.\n",
(unsigned) sizeof(tempStats.movelist) - 1);
}
safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
} else {
sprintf(tempStats.movelist, " no PV\n");
}
if (tempStats.seen_stat) {
tempStats.ok_to_send = 1;
}
if (strchr(tempStats.movelist, '(') != NULL) {
tempStats.line_is_book = 1;
tempStats.nr_moves = 0;
tempStats.moves_left = 0;
} else {
tempStats.line_is_book = 0;
}
if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
SendProgramStatsToFrontend( cps, &tempStats );
/*
[AS] Protect the thinkOutput buffer from overflow... this
is only useful if buf1 hasn't overflowed first!
*/
if((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(forwardMostMove)) curscore *= -1;
if(curscore >= MATE_SCORE)
snprintf(score_buf, MSG_SIZ, "#%d", curscore - MATE_SCORE);
else if(curscore <= -MATE_SCORE)
snprintf(score_buf, MSG_SIZ, "#%d", curscore + MATE_SCORE);
else
snprintf(score_buf, MSG_SIZ, "%+.2f", ((double) curscore) / 100.0);
snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%s %s%s",
plylev,
(gameMode == TwoMachinesPlay ?
ToUpper(cps->twoMachinesColor[0]) : ' '),
score_buf,
prefixHint ? lastHint : "",
prefixHint ? " " : "" );
if( buf1[0] != NULLCHAR ) {
unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
if( strlen(pv) > max_len ) {
if( appData.debugMode) {
fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
}
pv[max_len+1] = '\0';
}
strcat( thinkOutput, pv);
}
if (currentMove == forwardMostMove || gameMode == AnalyzeMode
|| gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
DisplayMove(currentMove - 1);
}
return;
} else if ((p=StrStr(message, "(only move)")) != NULL) {
/* crafty (9.25+) says "(only move) <move>"
* if there is only 1 legal move
*/
sscanf(p, "(only move) %s", buf1);
snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
sprintf(programStats.movelist, "%s (only move)", buf1);
programStats.depth = 1;
programStats.nr_moves = 1;
programStats.moves_left = 1;
programStats.nodes = 1;
programStats.time = 1;
programStats.got_only_move = 1;
/* Not really, but we also use this member to
mean "line isn't going to change" (Crafty
isn't searching, so stats won't change) */
programStats.line_is_book = 1;
SendProgramStatsToFrontend( cps, &programStats );
if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
DisplayMove(currentMove - 1);
}
return;
} else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
&time, &nodes, &plylev, &mvleft,
&mvtot, mvname) >= 5) {
/* The stat01: line is from Crafty (9.29+) in response
to the "." command */
programStats.seen_stat = 1;
cps->maybeThinking = TRUE;
if (programStats.got_only_move || !appData.periodicUpdates)
return;
programStats.depth = plylev;
programStats.time = time;
programStats.nodes = nodes;
programStats.moves_left = mvleft;
programStats.nr_moves = mvtot;
safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
programStats.ok_to_send = 1;
programStats.movelist[0] = '\0';
SendProgramStatsToFrontend( cps, &programStats );
return;
} else if (strncmp(message,"++",2) == 0) {
/* Crafty 9.29+ outputs this */
programStats.got_fail = 2;
return;
} else if (strncmp(message,"--",2) == 0) {
/* Crafty 9.29+ outputs this */
programStats.got_fail = 1;
return;
} else if (thinkOutput[0] != NULLCHAR &&
strncmp(message, " ", 4) == 0) {
unsigned message_len;
p = message;
while (*p && *p == ' ') p++;
message_len = strlen( p );
/* [AS] Avoid buffer overflow */
if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
strcat(thinkOutput, " ");
strcat(thinkOutput, p);
}
if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
strcat(programStats.movelist, " ");
strcat(programStats.movelist, p);
}
if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
DisplayMove(currentMove - 1);
}
return;
}
}
else {
buf1[0] = NULLCHAR;
if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
&plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
{
ChessProgramStats cpstats;
if (plyext != ' ' && plyext != '\t') {
time *= 100;
}
/* [AS] Negate score if machine is playing black and reporting absolute scores */
if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
curscore = -curscore;
}
cpstats.depth = plylev;
cpstats.nodes = nodes;
cpstats.time = time;
cpstats.score = curscore;
cpstats.got_only_move = 0;
cpstats.movelist[0] = '\0';
if (buf1[0] != NULLCHAR) {
safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
}
cpstats.ok_to_send = 0;
cpstats.line_is_book = 0;
cpstats.nr_moves = 0;
cpstats.moves_left = 0;
SendProgramStatsToFrontend( cps, &cpstats );
}
}
}
}
/* Parse a game score from the character string "game", and
record it as the history of the current game. The game
score is NOT assumed to start from the standard position.
The display is not updated in any way.
*/
void
ParseGameHistory (char *game)
{
ChessMove moveType;
int fromX, fromY, toX, toY, boardIndex;
char promoChar;
char *p, *q;
char buf[MSG_SIZ];
if (appData.debugMode)
fprintf(debugFP, "Parsing game history: %s\n", game);
if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
gameInfo.site = StrSave(appData.icsHost);
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
/* Parse out names of players */
while (*game == ' ') game++;
p = buf;
while (*game != ' ') *p++ = *game++;
*p = NULLCHAR;
gameInfo.white = StrSave(buf);
while (*game == ' ') game++;
p = buf;
while (*game != ' ' && *game != '\n') *p++ = *game++;
*p = NULLCHAR;
gameInfo.black = StrSave(buf);
/* Parse moves */
boardIndex = blackPlaysFirst ? 1 : 0;
yynewstr(game);
for (;;) {
yyboardindex = boardIndex;
moveType = (ChessMove) Myylex();
switch (moveType) {
case IllegalMove: /* maybe suicide chess, etc. */
if (appData.debugMode) {
fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
setbuf(debugFP, NULL);
}
case WhitePromotion:
case BlackPromotion:
case WhiteNonPromotion:
case BlackNonPromotion:
case NormalMove:
case FirstLeg:
case WhiteCapturesEnPassant:
case BlackCapturesEnPassant:
case WhiteKingSideCastle:
case WhiteQueenSideCastle:
case BlackKingSideCastle:
case BlackQueenSideCastle:
case WhiteKingSideCastleWild:
case WhiteQueenSideCastleWild:
case BlackKingSideCastleWild:
case BlackQueenSideCastleWild:
/* PUSH Fabien */
case WhiteHSideCastleFR:
case WhiteASideCastleFR:
case BlackHSideCastleFR:
case BlackASideCastleFR:
/* POP Fabien */
fromX = currentMoveString[0] - AAA;
fromY = currentMoveString[1] - ONE;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = currentMoveString[4];
break;
case WhiteDrop:
case BlackDrop:
if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
fromX = moveType == WhiteDrop ?
(int) CharToPiece(ToUpper(currentMoveString[0])) :
(int) CharToPiece(ToLower(currentMoveString[0]));
fromY = DROP_RANK;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = NULLCHAR;
break;
case AmbiguousMove:
/* bug? */
snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
if (appData.debugMode) {
fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
setbuf(debugFP, NULL);
}
DisplayError(buf, 0);
return;
case ImpossibleMove:
/* bug? */
snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
if (appData.debugMode) {
fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
setbuf(debugFP, NULL);
}
DisplayError(buf, 0);
return;
case EndOfFile:
if (boardIndex < backwardMostMove) {
/* Oops, gap. How did that happen? */
DisplayError(_("Gap in move list"), 0);
return;
}
backwardMostMove = blackPlaysFirst ? 1 : 0;
if (boardIndex > forwardMostMove) {
forwardMostMove = boardIndex;
}
return;
case ElapsedTime:
if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
strcat(parseList[boardIndex-1], " ");
strcat(parseList[boardIndex-1], yy_text);
}
continue;
case Comment:
case PGNTag:
case NAG:
default:
/* ignore */
continue;
case WhiteWins:
case BlackWins:
case GameIsDrawn:
case GameUnfinished:
if (gameMode == IcsExamining) {
if (boardIndex < backwardMostMove) {
/* Oops, gap. How did that happen? */
return;
}
backwardMostMove = blackPlaysFirst ? 1 : 0;
return;
}
gameInfo.result = moveType;
p = strchr(yy_text, '{');
if (p == NULL) p = strchr(yy_text, '(');
if (p == NULL) {
p = yy_text;
if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
} else {
q = strchr(p, *p == '{' ? '}' : ')');
if (q != NULL) *q = NULLCHAR;
p++;
}
while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
gameInfo.resultDetails = StrSave(p);
continue;
}
if (boardIndex >= forwardMostMove &&
!(gameMode == IcsObserving && ics_gamenum == -1)) {
backwardMostMove = blackPlaysFirst ? 1 : 0;
return;
}
(void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
fromY, fromX, toY, toX, promoChar,
parseList[boardIndex]);
CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
/* currentMoveString is set as a side-effect of yylex */
safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
strcat(moveList[boardIndex], "\n");
boardIndex++;
ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
case MT_NONE:
case MT_STALEMATE:
default:
break;
case MT_CHECK:
if(!IS_SHOGI(gameInfo.variant))
strcat(parseList[boardIndex - 1], "+");
break;
case MT_CHECKMATE:
case MT_STAINMATE:
strcat(parseList[boardIndex - 1], "#");
break;
}
}
}
/* Apply a move to the given board */
void
ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
{
ChessSquare captured = board[toY][toX], piece, pawn, king, killed, killed2; int p, rookX, oldEP, epRank, berolina = 0;
int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess ? 3 : 1;
/* [HGM] compute & store e.p. status and castling rights for new position */
/* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
oldEP = (signed char)board[EP_FILE]; epRank = board[EP_RANK];
board[EP_STATUS] = EP_NONE;
board[EP_FILE] = board[EP_RANK] = 100;
if (fromY == DROP_RANK) {
/* must be first */
if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
return;
}
piece = board[toY][toX] = (ChessSquare) fromX;
} else {
// ChessSquare victim;
int i;
if( killX >= 0 && killY >= 0 ) { // [HGM] lion: Lion trampled over something
// victim = board[killY][killX],
killed = board[killY][killX],
board[killY][killX] = EmptySquare,
board[EP_STATUS] = EP_CAPTURE;
if( kill2X >= 0 && kill2Y >= 0)
killed2 = board[kill2Y][kill2X], board[kill2Y][kill2X] = EmptySquare;
}
if( board[toY][toX] != EmptySquare ) {
board[EP_STATUS] = EP_CAPTURE;
if( (fromX != toX || fromY != toY) && // not igui!
(captured == WhiteLion && board[fromY][fromX] != BlackLion ||
captured == BlackLion && board[fromY][fromX] != WhiteLion ) ) { // [HGM] lion: Chu Lion-capture rules
board[EP_STATUS] = EP_IRON_LION; // non-Lion x Lion: no counter-strike allowed
}
}
pawn = board[fromY][fromX];
if( pawn == WhiteLance || pawn == BlackLance ) {
if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu ) {
if(gameInfo.variant == VariantSpartan) board[EP_STATUS] = EP_PAWN_MOVE; // in Spartan no e.p. rights must be set
else pawn += WhitePawn - WhiteLance; // Lance is Pawn-like in most variants, so let Pawn code treat it by this kludge
}
}
if( pawn == WhitePawn ) {
if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
board[EP_STATUS] = EP_PAWN_MOVE;
if( toY-fromY>=2) {
board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY - 1 | 128*(toY - fromY > 2);
if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
gameInfo.variant != VariantBerolina || toX < fromX)
board[EP_STATUS] = toX | berolina;
if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
gameInfo.variant != VariantBerolina || toX > fromX)
board[EP_STATUS] = toX;
}
} else
if( pawn == BlackPawn ) {
if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
board[EP_STATUS] = EP_PAWN_MOVE;
if( toY-fromY<= -2) {
board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY + 1 | 128*(fromY - toY > 2);
if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
gameInfo.variant != VariantBerolina || toX < fromX)
board[EP_STATUS] = toX | berolina;
if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
gameInfo.variant != VariantBerolina || toX > fromX)
board[EP_STATUS] = toX;
}
}
if(fromY == 0) board[TOUCHED_W] |= 1<<fromX; else // new way to keep track of virginity
if(fromY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<fromX;
if(toY == 0) board[TOUCHED_W] |= 1<<toX; else
if(toY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<toX;
for(i=0; i<nrCastlingRights; i++) {
if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
board[CASTLING][i] == toX && castlingRank[i] == toY
) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
}
if(gameInfo.variant == VariantSChess) { // update virginity
if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
}
if (fromX == toX && fromY == toY && killX < 0) return;
piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
if(gameInfo.variant == VariantKnightmate)
king += (int) WhiteUnicorn - (int) WhiteKing;
if(pieceDesc[piece] && killX >= 0 && strchr(pieceDesc[piece], 'O') // Betza castling-enabled
&& (piece < BlackPawn ? killed < BlackPawn : killed >= BlackPawn)) { // and tramples own
board[toY][toX] = piece; board[fromY][fromX] = EmptySquare;
board[toY][toX + (killX < fromX ? 1 : -1)] = killed;
board[EP_STATUS] = EP_NONE; // capture was fake!
} else
if(nrCastlingRights == 0 && board[toY][toX] < EmptySquare && (piece < BlackPawn) == (board[toY][toX] < BlackPawn)) {
board[fromY][fromX] = board[toY][toX]; // capture own will lead to swapping
board[toY][toX] = piece;
board[EP_STATUS] = EP_NONE; // capture was fake!
} else
/* Code added by Tord: */
/* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
board[EP_STATUS] = EP_NONE; // capture was fake!
board[fromY][fromX] = EmptySquare;
board[toY][toX] = EmptySquare;
if((toX > fromX) != (piece == WhiteRook)) {
board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
} else {
board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
}
} else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
board[EP_STATUS] = EP_NONE;
board[fromY][fromX] = EmptySquare;
board[toY][toX] = EmptySquare;
if((toX > fromX) != (piece == BlackRook)) {
board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
} else {
board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
}
/* End of code added by Tord */
} else if (pieceDesc[piece] && piece == king && !strchr(pieceDesc[piece], 'O') && strchr(pieceDesc[piece], 'i')) {
board[fromY][fromX] = EmptySquare; // never castle if King has virgin moves defined on it other than castling
board[toY][toX] = piece;
} else if (board[fromY][fromX] == king
&& fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
&& toY == fromY && toX > fromX+1) {
for(rookX=fromX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT-1; rookX++)
; // castle with nearest piece
board[fromY][toX-1] = board[fromY][rookX];
board[fromY][rookX] = EmptySquare;
board[fromY][fromX] = EmptySquare;
board[toY][toX] = king;
} else if (board[fromY][fromX] == king
&& fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
&& toY == fromY && toX < fromX-1) {
for(rookX=fromX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
; // castle with nearest piece
board[fromY][toX+1] = board[fromY][rookX];
board[fromY][rookX] = EmptySquare;
board[fromY][fromX] = EmptySquare;
board[toY][toX] = king;
} else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
&& toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
) {
/* white pawn promotion */
board[toY][toX] = CharToPiece(ToUpper(promoChar));
if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
board[fromY][fromX] = EmptySquare;
} else if ((fromY >= BOARD_HEIGHT>>1)
&& (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
&& (toX != fromX)
&& gameInfo.variant != VariantXiangqi
&& gameInfo.variant != VariantBerolina
&& (pawn == WhitePawn)
&& (board[toY][toX] == EmptySquare)) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = piece;
if(toY == epRank - 128 + 1)
captured = board[toY - 2][toX], board[toY - 2][toX] = EmptySquare;
else
captured = board[toY - 1][toX], board[toY - 1][toX] = EmptySquare;
} else if ((fromY == BOARD_HEIGHT-4)
&& (toX == fromX)
&& gameInfo.variant == VariantBerolina
&& (board[fromY][fromX] == WhitePawn)
&& (board[toY][toX] == EmptySquare)) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = WhitePawn;
if(oldEP & EP_BEROLIN_A) {
captured = board[fromY][fromX-1];
board[fromY][fromX-1] = EmptySquare;
}else{ captured = board[fromY][fromX+1];
board[fromY][fromX+1] = EmptySquare;
}
} else if (board[fromY][fromX] == king
&& fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
&& toY == fromY && toX > fromX+1) {
for(rookX=toX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT - 1; rookX++)
;
board[fromY][toX-1] = board[fromY][rookX];
board[fromY][rookX] = EmptySquare;
board[fromY][fromX] = EmptySquare;
board[toY][toX] = king;
} else if (board[fromY][fromX] == king
&& fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
&& toY == fromY && toX < fromX-1) {
for(rookX=toX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
;
board[fromY][toX+1] = board[fromY][rookX];
board[fromY][rookX] = EmptySquare;
board[fromY][fromX] = EmptySquare;
board[toY][toX] = king;
} else if (fromY == 7 && fromX == 3
&& board[fromY][fromX] == BlackKing
&& toY == 7 && toX == 5) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = BlackKing;
board[fromY][7] = EmptySquare;
board[toY][4] = BlackRook;
} else if (fromY == 7 && fromX == 3
&& board[fromY][fromX] == BlackKing
&& toY == 7 && toX == 1) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = BlackKing;
board[fromY][0] = EmptySquare;
board[toY][2] = BlackRook;
} else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
&& toY < promoRank && promoChar
) {
/* black pawn promotion */
board[toY][toX] = CharToPiece(ToLower(promoChar));
if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
board[fromY][fromX] = EmptySquare;
} else if ((fromY < BOARD_HEIGHT>>1)
&& (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
&& (toX != fromX)
&& gameInfo.variant != VariantXiangqi
&& gameInfo.variant != VariantBerolina
&& (pawn == BlackPawn)
&& (board[toY][toX] == EmptySquare)) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = piece;
if(toY == epRank - 128 - 1)
captured = board[toY + 2][toX], board[toY + 2][toX] = EmptySquare;
else
captured = board[toY + 1][toX], board[toY + 1][toX] = EmptySquare;
} else if ((fromY == 3)
&& (toX == fromX)
&& gameInfo.variant == VariantBerolina
&& (board[fromY][fromX] == BlackPawn)
&& (board[toY][toX] == EmptySquare)) {
board[fromY][fromX] = EmptySquare;
board[toY][toX] = BlackPawn;
if(oldEP & EP_BEROLIN_A) {
captured = board[fromY][fromX-1];
board[fromY][fromX-1] = EmptySquare;
}else{ captured = board[fromY][fromX+1];
board[fromY][fromX+1] = EmptySquare;
}
} else {
ChessSquare piece = board[fromY][fromX]; // [HGM] lion: allow for igui (where from == to)
board[fromY][fromX] = EmptySquare;
board[toY][toX] = piece;
}
}
if (gameInfo.holdingsWidth != 0) {
/* !!A lot more code needs to be written to support holdings */
/* [HGM] OK, so I have written it. Holdings are stored in the */
/* penultimate board files, so they are automaticlly stored */
/* in the game history. */
if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
&& promoChar && piece != WhitePawn && piece != BlackPawn) {
/* Delete from holdings, by decreasing count */
/* and erasing image if necessary */
p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
if(p < (int) BlackPawn) { /* white drop */
p -= (int)WhitePawn;
p = PieceToNumber((ChessSquare)p);
if(p >= gameInfo.holdingsSize) p = 0;
if(--board[p][BOARD_WIDTH-2] <= 0)
board[p][BOARD_WIDTH-1] = EmptySquare;
if((int)board[p][BOARD_WIDTH-2] < 0)
board[p][BOARD_WIDTH-2] = 0;
} else { /* black drop */
p -= (int)BlackPawn;
p = PieceToNumber((ChessSquare)p);
if(p >= gameInfo.holdingsSize) p = 0;
if(--board[BOARD_HEIGHT-1-p][1] <= 0)
board[BOARD_HEIGHT-1-p][0] = EmptySquare;
if((int)board[BOARD_HEIGHT-1-p][1] < 0)
board[BOARD_HEIGHT-1-p][1] = 0;
}
}
if (captured != EmptySquare && gameInfo.holdingsSize > 0
&& gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
/* [HGM] holdings: Add to holdings, if holdings exist */
if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
// [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
}
p = (int) captured;
if (p >= (int) BlackPawn) {
p -= (int)BlackPawn;
if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
/* Restore shogi-promoted piece to its original first */
captured = (ChessSquare) (DEMOTED(captured));
p = DEMOTED(p);
}
p = PieceToNumber((ChessSquare)p);
if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
board[p][BOARD_WIDTH-2]++;
board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
} else {
p -= (int)WhitePawn;
if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
captured = (ChessSquare) (DEMOTED(captured));
p = DEMOTED(p);
}
p = PieceToNumber((ChessSquare)p);
if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
board[BOARD_HEIGHT-1-p][1]++;
board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
}
}
} else if (gameInfo.variant == VariantAtomic) {
if (captured != EmptySquare) {
int y, x;
for (y = toY-1; y <= toY+1; y++) {
for (x = toX-1; x <= toX+1; x++) {
if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
board[y][x] = EmptySquare;
}
}
}
board[toY][toX] = EmptySquare;
}
}
if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
} else
if(promoChar == '+') {
/* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
board[toY][toX] = (ChessSquare) (CHUPROMOTED(piece));
if(gameInfo.variant == VariantChuChess && (piece == WhiteKnight || piece == BlackKnight))
board[toY][toX] = piece + WhiteLion - WhiteKnight; // adjust Knight promotions to Lion
} else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
&& pieceToChar[PROMOTED(newPiece)] == '~') newPiece = PROMOTED(newPiece);// but promoted version available
board[toY][toX] = newPiece;
}
if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
&& promoChar != NULLCHAR && gameInfo.holdingsSize) {
// [HGM] superchess: take promotion piece out of holdings
int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
if((int)piece < (int)BlackPawn) { // determine stm from piece color
if(!--board[k][BOARD_WIDTH-2])
board[k][BOARD_WIDTH-1] = EmptySquare;
} else {
if(!--board[BOARD_HEIGHT-1-k][1])
board[BOARD_HEIGHT-1-k][0] = EmptySquare;
}
}
}
/* Updates forwardMostMove */
void
MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
{
int x = toX, y = toY;
char *s = parseList[forwardMostMove];
ChessSquare p = boards[forwardMostMove][toY][toX];
// forwardMostMove++; // [HGM] bare: moved downstream
if(kill2X >= 0) x = kill2X, y = kill2Y; else
if(killX >= 0 && killY >= 0) x = killX, y = killY; // [HGM] lion: make SAN move to intermediate square, if there is one
(void) CoordsToAlgebraic(boards[forwardMostMove],
PosFlags(forwardMostMove),
fromY, fromX, y, x, (killX < 0)*promoChar,
s);
if(kill2X >= 0 && kill2Y >= 0)
sprintf(s + strlen(s), "x%c%d", killX + AAA, killY + ONE - '0'); // 2nd leg of 3-leg move is always capture
if(killX >= 0 && killY >= 0)
sprintf(s + strlen(s), "%c%c%d%c", p == EmptySquare || toX == fromX && toY == fromY || toX== kill2X && toY == kill2Y ? '-' : 'x',
toX + AAA, toY + ONE - '0', promoChar);
if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
int timeLeft; static int lastLoadFlag=0; int king, piece;
piece = boards[forwardMostMove][fromY][fromX];
king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
if(gameInfo.variant == VariantKnightmate)
king += (int) WhiteUnicorn - (int) WhiteKing;
if(forwardMostMove == 0) {
if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
fprintf(serverMoves, "%s;", UserName());
else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
fprintf(serverMoves, "%s;", second.tidy);
fprintf(serverMoves, "%s;", first.tidy);
if(gameMode == MachinePlaysWhite)
fprintf(serverMoves, "%s;", UserName());
else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
fprintf(serverMoves, "%s;", second.tidy);
} else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
lastLoadFlag = loadFlag;
// print base move
fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
// print castling suffix
if( toY == fromY && piece == king ) {
if(toX-fromX > 1)
fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
if(fromX-toX >1)
fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
}
// e.p. suffix
if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
boards[forwardMostMove][toY][toX] == EmptySquare
&& fromX != toX && fromY != toY)
fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
// promotion suffix
if(promoChar != NULLCHAR) {
if(fromY == 0 || fromY == BOARD_HEIGHT-1)
fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
}
if(!loadFlag) {
char buf[MOVE_LEN*2], *p; int len;
fprintf(serverMoves, "/%d/%d",
pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
else timeLeft = blackTimeRemaining/1000;
fprintf(serverMoves, "/%d", timeLeft);
strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
if(p = strchr(buf, '/')) *p = NULLCHAR; else
if(p = strchr(buf, '=')) *p = NULLCHAR;
len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
fprintf(serverMoves, "/%s", buf);
}
fflush(serverMoves);
}
if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
return;
}
UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
if (commentList[forwardMostMove+1] != NULL) {
free(commentList[forwardMostMove+1]);
commentList[forwardMostMove+1] = NULL;
}
CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
// forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
timeRemaining[1][forwardMostMove] = blackTimeRemaining;
adjustedClock = FALSE;
gameInfo.result = GameUnfinished;
if (gameInfo.resultDetails != NULL) {
free(gameInfo.resultDetails);
gameInfo.resultDetails = NULL;
}
CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
moveList[forwardMostMove - 1]);
switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
case MT_NONE:
case MT_STALEMATE:
default:
break;
case MT_CHECK:
if(!IS_SHOGI(gameInfo.variant))
strcat(parseList[forwardMostMove - 1], "+");
break;
case MT_CHECKMATE:
case MT_STAINMATE:
strcat(parseList[forwardMostMove - 1], "#");
break;
}
}
/* Updates currentMove if not pausing */
void
ShowMove (int fromX, int fromY, int toX, int toY)
{
int instant = (gameMode == PlayFromGameFile) ?
(matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
if(appData.noGUI) return;
if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
if (!instant) {
if (forwardMostMove == currentMove + 1) {
AnimateMove(boards[forwardMostMove - 1],
fromX, fromY, toX, toY);
}
}
currentMove = forwardMostMove;
}
killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
if (instant) return;
DisplayMove(currentMove - 1);
if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
SetHighlights(fromX, fromY, toX, toY);
}
}
DrawPosition(FALSE, boards[currentMove]);
DisplayBothClocks();
HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
}
void
SendEgtPath (ChessProgramState *cps)
{ /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
char buf[MSG_SIZ], name[MSG_SIZ], *p;
if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
while(*p) {
char c, *q = name+1, *r, *s;
name[0] = ','; // extract next format name from feature and copy with prefixed ','
while(*p && *p != ',') *q++ = *p++;
*q++ = ':'; *q = 0;
if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
strcmp(name, ",nalimov:") == 0 ) {
// take nalimov path from the menu-changeable option first, if it is defined
snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
SendToProgram(buf,cps); // send egtbpath command for nalimov
} else
if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
(s = StrStr(appData.egtFormats, name)) != NULL) {
// format name occurs amongst user-supplied formats, at beginning or immediately after comma
s = r = StrStr(s, ":") + 1; // beginning of path info
while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
c = *r; *r = 0; // temporarily null-terminate path info
*--q = 0; // strip of trailig ':' from name
snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
*r = c;
SendToProgram(buf,cps); // send egtbpath command for this format
}
if(*p == ',') p++; // read away comma to position for next format name
}
}
static int
NonStandardBoardSize (VariantClass v, int boardWidth, int boardHeight, int holdingsSize)
{
int width = 8, height = 8, holdings = 0; // most common sizes
if( v == VariantUnknown || *engineVariant) return 0; // engine-defined name never needs prefix
// correct the deviations default for each variant
if( v == VariantXiangqi ) width = 9, height = 10;
if( v == VariantShogi ) width = 9, height = 9, holdings = 7;
if( v == VariantBughouse || v == VariantCrazyhouse) holdings = 5;
if( v == VariantCapablanca || v == VariantCapaRandom ||
v == VariantGothic || v == VariantFalcon || v == VariantJanus )
width = 10;
if( v == VariantCourier ) width = 12;
if( v == VariantSuper ) holdings = 8;
if( v == VariantGreat ) width = 10, holdings = 8;
if( v == VariantSChess ) holdings = 7;
if( v == VariantGrand ) width = 10, height = 10, holdings = 7;
if( v == VariantChuChess) width = 10, height = 10;
if( v == VariantChu ) width = 12, height = 12;
return boardWidth >= 0 && boardWidth != width || // -1 is default,
boardHeight >= 0 && boardHeight != height || // and thus by definition OK
holdingsSize >= 0 && holdingsSize != holdings;
}
char variantError[MSG_SIZ];
char *
SupportedVariant (char *list, VariantClass v, int boardWidth, int boardHeight, int holdingsSize, int proto, char *engine)
{ // returns error message (recognizable by upper-case) if engine does not support the variant
char *p, *variant = VariantName(v);
static char b[MSG_SIZ];
if(NonStandardBoardSize(v, boardWidth, boardHeight, holdingsSize)) { /* [HGM] make prefix for non-standard board size. */
snprintf(b, MSG_SIZ, "%dx%d+%d_%s", boardWidth, boardHeight,
holdingsSize, variant); // cook up sized variant name
/* [HGM] varsize: try first if this deviant size variant is specifically known */
if(StrStr(list, b) == NULL) {
// specific sized variant not known, check if general sizing allowed
if(proto != 1 && StrStr(list, "boardsize") == NULL) {
snprintf(variantError, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
boardWidth, boardHeight, holdingsSize, engine);
return NULL;
}
/* [HGM] here we really should compare with the maximum supported board size */
}
} else snprintf(b, MSG_SIZ,"%s", variant);
if(proto == 1) return b; // for protocol 1 we cannot check and hope for the best
p = StrStr(list, b);
while(p && (p != list && p[-1] != ',' || p[strlen(b)] && p[strlen(b)] != ',') ) p = StrStr(p+1, b);
if(p == NULL) {
// occurs not at all in list, or only as sub-string
snprintf(variantError, MSG_SIZ, _("Variant %s not supported by %s"), b, engine);
if(p = StrStr(list, b)) { // handle requesting parent variant when only size-overridden is supported
int l = strlen(variantError);
char *q;
while(p != list && p[-1] != ',') p--;
q = strchr(p, ',');
if(q) *q = NULLCHAR;
snprintf(variantError + l, MSG_SIZ - l, _(", but %s is"), p);
if(q) *q= ',';
}
return NULL;
}
return b;
}
void
InitChessProgram (ChessProgramState *cps, int setup)
/* setup needed to setup FRC opening position */
{
char buf[MSG_SIZ], *b;
if (appData.noChessProgram) return;
hintRequested = FALSE;
bookRequested = FALSE;
ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
/* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
/* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
if(cps->memSize) { /* [HGM] memory */
snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
SendToProgram(buf, cps);
}
SendEgtPath(cps); /* [HGM] EGT */
if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
SendToProgram(buf, cps);
}
setboardSpoiledMachineBlack = FALSE;
SendToProgram(cps->initString, cps);
if (gameInfo.variant != VariantNormal &&
gameInfo.variant != VariantLoadable
/* [HGM] also send variant if board size non-standard */
|| gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0) {
b = SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, cps->tidy);
if (b == NULL) {
VariantClass v;
char c, *q = cps->variants, *p = strchr(q, ',');
if(p) *p = NULLCHAR;
v = StringToVariant(q);
DisplayError(variantError, 0);
if(v != VariantUnknown && cps == &first) {
int w, h, s;
if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
ASSIGN(appData.variant, q);
Reset(TRUE, FALSE);
}
if(p) *p = ',';
return;
}
snprintf(buf, MSG_SIZ, "variant %s\n", b);
SendToProgram(buf, cps);
}
currentlyInitializedVariant = gameInfo.variant;
/* [HGM] send opening position in FRC to first engine */
if(setup) {
SendToProgram("force\n", cps);
SendBoard(cps, 0);
/* engine is now in force mode! Set flag to wake it up after first move. */
setboardSpoiledMachineBlack = 1;
}
if (cps->sendICS) {
snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
SendToProgram(buf, cps);
}
cps->maybeThinking = FALSE;
cps->offeredDraw = 0;
if (!appData.icsActive) {
SendTimeControl(cps, movesPerSession, timeControl,
timeIncrement, appData.searchDepth,
searchTime);
}
if (appData.showThinking
// [HGM] thinking: four options require thinking output to be sent
|| !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
) {
SendToProgram("post\n", cps);
}
SendToProgram("hard\n", cps);
if (!appData.ponderNextMove) {
/* Warning: "easy" is a toggle in GNU Chess, so don't send
it without being sure what state we are in first. "hard"
is not a toggle, so that one is OK.
*/
SendToProgram("easy\n", cps);
}
if (cps->usePing) {
snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++cps->lastPing);
SendToProgram(buf, cps);
}
cps->initDone = TRUE;
ClearEngineOutputPane(cps == &second);
}
void
ResendOptions (ChessProgramState *cps)
{ // send the stored value of the options
int i;
char buf[MSG_SIZ];
Option *opt = cps->option;
for(i=0; i<cps->nrOptions; i++, opt++) {
switch(opt->type) {
case Spin:
case Slider:
case CheckBox:
snprintf(buf, MSG_SIZ, "option %s=%d\n", opt->name, opt->value);
break;
case ComboBox:
snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->choice[opt->value]);
break;
default:
snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->textValue);
break;
case Button:
case SaveButton:
continue;
}
SendToProgram(buf, cps);
}
}
void
StartChessProgram (ChessProgramState *cps)
{
char buf[MSG_SIZ];
int err;
if (appData.noChessProgram) return;
cps->initDone = FALSE;
if (strcmp(cps->host, "localhost") == 0) {
err = StartChildProcess(cps->program, cps->dir, &cps->pr);
} else if (*appData.remoteShell == NULLCHAR) {
err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
} else {
if (*appData.remoteUser == NULLCHAR) {
snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
cps->program);
} else {
snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
cps->host, appData.remoteUser, cps->program);
}
err = StartChildProcess(buf, "", &cps->pr);
}
if (err != 0) {
snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
if(cps != &first) return;
appData.noChessProgram = TRUE;
ThawUI();
SetNCPMode();
// DisplayFatalError(buf, err, 1);
// cps->pr = NoProc;
// cps->isr = NULL;
return;
}
cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
if (cps->protocolVersion > 1) {
snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
if(!cps->reload) { // do not clear options when reloading because of -xreuse
cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
cps->comboCnt = 0; // and values of combo boxes
}
SendToProgram(buf, cps);
if(cps->reload) ResendOptions(cps);
} else {
SendToProgram("xboard\n", cps);
}
}
void
TwoMachinesEventIfReady P((void))
{
static int curMess = 0;
if (first.lastPing != first.lastPong) {
if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
return;
}
if (second.lastPing != second.lastPong) {
if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
return;
}
DisplayMessage("", ""); curMess = 0;
TwoMachinesEvent();
}
char *
MakeName (char *template)
{
time_t clock;
struct tm *tm;
static char buf[MSG_SIZ];
char *p = buf;
int i;
clock = time((time_t *)NULL);
tm = localtime(&clock);
while(*p++ = *template++) if(p[-1] == '%') {
switch(*template++) {
case 0: *p = 0; return buf;
case 'Y': i = tm->tm_year+1900; break;
case 'y': i = tm->tm_year-100; break;
case 'M': i = tm->tm_mon+1; break;
case 'd': i = tm->tm_mday; break;
case 'h': i = tm->tm_hour; break;
case 'm': i = tm->tm_min; break;
case 's': i = tm->tm_sec; break;
default: i = 0;
}
snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
}
return buf;
}
int
CountPlayers (char *p)
{
int n = 0;
while(p = strchr(p, '\n')) p++, n++; // count participants
return n;
}
FILE *
WriteTourneyFile (char *results, FILE *f)
{ // write tournament parameters on tourneyFile; on success return the stream pointer for closing
if(f == NULL) f = fopen(appData.tourneyFile, "w");
if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
// create a file with tournament description
fprintf(f, "-participants {%s}\n", appData.participants);
fprintf(f, "-seedBase %d\n", appData.seedBase);
fprintf(f, "-tourneyType %d\n", appData.tourneyType);
fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
fprintf(f, "-bookDepth %d\n", appData.bookDepth);
fprintf(f, "-bookVariation %d\n", appData.bookStrength);
fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
fprintf(f, "-smpCores %d\n", appData.smpCores);
if(searchTime > 0)
fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
else {
fprintf(f, "-mps %d\n", appData.movesPerSession);
fprintf(f, "-tc %s\n", appData.timeControl);
fprintf(f, "-inc %.2f\n", appData.timeIncrement);
}
fprintf(f, "-results \"%s\"\n", results);
}
return f;
}
char *command[MAXENGINES], *mnemonic[MAXENGINES];
void
Substitute (char *participants, int expunge)
{
int i, changed, changes=0, nPlayers=0;
char *p, *q, *r, buf[MSG_SIZ];
if(participants == NULL) return;
if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
r = p = participants; q = appData.participants;
while(*p && *p == *q) {
if(*p == '\n') r = p+1, nPlayers++;
p++; q++;
}
if(*p) { // difference
while(*p && *p++ != '\n')
;
while(*q && *q++ != '\n')
;
changed = nPlayers;
changes = 1 + (strcmp(p, q) != 0);
}
if(changes == 1) { // a single engine mnemonic was changed
q = r; while(*q) nPlayers += (*q++ == '\n');
p = buf; while(*r && (*p = *r++) != '\n') p++;
*p = NULLCHAR;
NamesToList(firstChessProgramNames, command, mnemonic, "all");
for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
if(mnemonic[i]) { // The substitute is valid
FILE *f;
if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
flock(fileno(f), LOCK_EX);
ParseArgsFromFile(f);
fseek(f, 0, SEEK_SET);
FREE(appData.participants); appData.participants = participants;
if(expunge) { // erase results of replaced engine
int len = strlen(appData.results), w, b, dummy;
for(i=0; i<len; i++) {
Pairing(i, nPlayers, &w, &b, &dummy);
if((w == changed || b == changed) && appData.results[i] == '*') {
DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
fclose(f);
return;
}
}
for(i=0; i<len; i++) {
Pairing(i, nPlayers, &w, &b, &dummy);
if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
}
}
WriteTourneyFile(appData.results, f);
fclose(f); // release lock
return;
}
} else DisplayError(_("No engine with the name you gave is installed"), 0);
}
if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
free(participants);
return;
}
int
CheckPlayers (char *participants)
{
int i;
char buf[MSG_SIZ], *p;
NamesToList(firstChessProgramNames, command, mnemonic, "all");
while(p = strchr(participants, '\n')) {
*p = NULLCHAR;
for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
if(!mnemonic[i]) {
snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
*p = '\n';
DisplayError(buf, 0);
return 1;
}
*p = '\n';
participants = p + 1;
}
return 0;
}
int
CreateTourney (char *name)
{
FILE *f;
if(matchMode && strcmp(name, appData.tourneyFile)) {
ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
}
if(name[0] == NULLCHAR) {
if(appData.participants[0])
DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
return 0;
}
f = fopen(name, "r");
if(f) { // file exists
ASSIGN(appData.tourneyFile, name);
ParseArgsFromFile(f); // parse it
} else {
if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
DisplayError(_("Not enough participants"), 0);
return 0;
}
if(CheckPlayers(appData.participants)) return 0;
ASSIGN(appData.tourneyFile, name);
if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
}
fclose(f);
appData.noChessProgram = FALSE;
appData.clockMode = TRUE;
SetGNUMode();
return 1;
}
int
NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
{
char buf[2*MSG_SIZ], *p, *q;
int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
skip = !all && group[0]; // if group requested, we start in skip mode
for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
p = names; q = buf; header = 0;
while(*p && *p != '\n') *q++ = *p++;
*q = 0;
if(*p == '\n') p++;
if(buf[0] == '#') {
if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
depth++; // we must be entering a new group
if(all) continue; // suppress printing group headers when complete list requested
header = 1;
if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
}
if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
if(engineList[i]) free(engineList[i]);
engineList[i] = strdup(buf);
if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
if(engineMnemonic[i]) free(engineMnemonic[i]);
if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
strcat(buf, " (");
sscanf(q + 8, "%s", buf + strlen(buf));
strcat(buf, ")");
}
engineMnemonic[i] = strdup(buf);
i++;
}
engineList[i] = engineMnemonic[i] = NULL;
return i;
}
// following implemented as macro to avoid type limitations
#define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
void
SwapEngines (int n)
{ // swap settings for first engine and other engine (so far only some selected options)
int h;
char *p;
if(n == 0) return;
SWAP(directory, p)
SWAP(chessProgram, p)
SWAP(isUCI, h)
SWAP(hasOwnBookUCI, h)
SWAP(protocolVersion, h)
SWAP(reuse, h)
SWAP(scoreIsAbsolute, h)
SWAP(timeOdds, h)
SWAP(logo, p)
SWAP(pgnName, p)
SWAP(pvSAN, h)
SWAP(engOptions, p)
SWAP(engInitString, p)
SWAP(computerString, p)
SWAP(features, p)
SWAP(fenOverride, p)
SWAP(NPS, h)
SWAP(accumulateTC, h)
SWAP(drawDepth, h)
SWAP(host, p)
SWAP(pseudo, h)
}
int
GetEngineLine (char *s, int n)
{
int i;
char buf[MSG_SIZ];
extern char *icsNames;
if(!s || !*s) return 0;
NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
if(!mnemonic[i]) return 0;
if(n == 11) return 1; // just testing if there was a match
snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
if(n == 1) SwapEngines(n);
ParseArgsFromString(buf);
if(n == 1) SwapEngines(n);
if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
ParseArgsFromString(buf);
}
return 1;
}
int
SetPlayer (int player, char *p)
{ // [HGM] find the engine line of the partcipant given by number, and parse its options.
int i;
char buf[MSG_SIZ], *engineName;
for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
if(mnemonic[i]) {
snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
ParseArgsFromString(buf);
} else { // no engine with this nickname is installed!
snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
ModeHighlight();
DisplayError(buf, 0);
return 0;
}
free(engineName);
return i;
}
char *recentEngines;
void
RecentEngineEvent (int nr)
{
int n;
// SwapEngines(1); // bump first to second
// ReplaceEngine(&second, 1); // and load it there
NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
ReplaceEngine(&first, 0);
FloatToFront(&appData.recentEngineList, command[n]);
}
}
int
Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
{ // determine players from game number
int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
if(appData.tourneyType == 0) {
roundsPerCycle = (nPlayers - 1) | 1;
pairingsPerRound = nPlayers / 2;
} else if(appData.tourneyType > 0) {
roundsPerCycle = nPlayers - appData.tourneyType;
pairingsPerRound = appData.tourneyType;
}
gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
gamesPerCycle = gamesPerRound * roundsPerCycle;
appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
curRound = nr / gamesPerRound; nr %= gamesPerRound;
curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
if(appData.cycleSync) *syncInterval = gamesPerCycle;
if(appData.roundSync) *syncInterval = gamesPerRound;
if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
if(appData.tourneyType == 0) {
if(curPairing == (nPlayers-1)/2 ) {
*whitePlayer = curRound;
*blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
} else {
*whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
*blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
}
} else if(appData.tourneyType > 1) {
*blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
*whitePlayer = curRound + appData.tourneyType;
} else if(appData.tourneyType > 0) {
*whitePlayer = curPairing;
*blackPlayer = curRound + appData.tourneyType;
}
// take care of white/black alternation per round.
// For cycles and games this is already taken care of by default, derived from matchGame!
return curRound & 1;
}
int
NextTourneyGame (int nr, int *swapColors)
{ // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
char *p, *q;
int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
FILE *tf;
if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
tf = fopen(appData.tourneyFile, "r");
if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
ParseArgsFromFile(tf); fclose(tf);
InitTimeControls(); // TC might be altered from tourney file
nPlayers = CountPlayers(appData.participants); // count participants
if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
*swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
if(syncInterval) {
p = q = appData.results;
while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
if(firstBusy/syncInterval < (nextGame/syncInterval)) {
DisplayMessage(_("Waiting for other game(s)"),"");
waitingForGame = TRUE;
ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
return 0;
}
waitingForGame = FALSE;
}
if(appData.tourneyType < 0) {
if(nr>=0 && !pairingReceived) {
char buf[1<<16];
if(pairing.pr == NoProc) {
if(!appData.pairingEngine[0]) {
DisplayFatalError(_("No pairing engine specified"), 0, 1);
return 0;
}
StartChessProgram(&pairing); // starts the pairing engine
}
snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
SendToProgram(buf, &pairing);
snprintf(buf, 1<<16, "pairing %d\n", nr+1);
SendToProgram(buf, &pairing);
return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
}
pairingReceived = 0; // ... so we continue here
*swapColors = 0;
appData.matchGames = appData.tourneyCycles * syncInterval - 1;
whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
matchGame = 1; roundNr = nr / syncInterval + 1;
}
if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
// redefine engines, engine dir, etc.
NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
if(first.pr == NoProc) {
if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
}
if(second.pr == NoProc) {
SwapEngines(1);
if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
SwapEngines(1); // and make that valid for second engine by swapping
InitEngine(&second, 1);
}
CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
UpdateLogos(FALSE); // leave display to ModeHiglight()
return OK;
}
void
NextMatchGame ()
{ // performs game initialization that does not invoke engines, and then tries to start the game
int res, firstWhite, swapColors = 0;
if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
if(matchMode && appData.debugMode) { // [HGM] debug split: game is part of a match; we might have to create a debug file just for this game
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
if(strcmp(buf, currentDebugFile)) { // name has changed
FILE *f = fopen(buf, "w");
if(f) { // if opening the new file failed, just keep using the old one
ASSIGN(currentDebugFile, buf);
fclose(debugFP);
debugFP = f;
}
if(appData.serverFileName) {
if(serverFP) fclose(serverFP);
serverFP = fopen(appData.serverFileName, "w");
if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
}
}
}
firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
Reset(FALSE, first.pr != NoProc);
res = LoadGameOrPosition(matchGame); // setup game
appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
if(!res) return; // abort when bad game/pos file
if(appData.epd) {// in EPD mode we make sure first engine is to move
firstWhite = !(forwardMostMove & 1);
first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
}
TwoMachinesEvent();
}
void
UserAdjudicationEvent (int result)
{
ChessMove gameResult = GameIsDrawn;
if( result > 0 ) {
gameResult = WhiteWins;
}
else if( result < 0 ) {
gameResult = BlackWins;
}
if( gameMode == TwoMachinesPlay ) {
GameEnds( gameResult, "User adjudication", GE_XBOARD );
}
}
// [HGM] save: calculate checksum of game to make games easily identifiable
int
StringCheckSum (char *s)
{
int i = 0;
if(s==NULL) return 0;
while(*s) i = i*259 + *s++;
return i;
}
int
GameCheckSum ()
{
int i, sum=0;
for(i=backwardMostMove; i<forwardMostMove; i++) {
sum += pvInfoList[i].depth;
sum += StringCheckSum(parseList[i]);
sum += StringCheckSum(commentList[i]);
sum *= 261;
}
if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
return sum + StringCheckSum(commentList[i]);
} // end of save patch
void
GameEnds (ChessMove result, char *resultDetails, int whosays)
{
GameMode nextGameMode;
int isIcsGame;
char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
if(endingGame) return; /* [HGM] crash: forbid recursion */
endingGame = 1;
if(twoBoards) { // [HGM] dual: switch back to one board
twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
}
if (appData.debugMode) {
fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
result, resultDetails ? resultDetails : "(null)", whosays);
}
fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move the user is entering. // [HGM] lion
if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
/* If we are playing on ICS, the server decides when the
game is over, but the engine can offer to draw, claim
a draw, or resign.
*/
#if ZIPPY
if (appData.zippyPlay && first.initDone) {
if (result == GameIsDrawn) {
/* In case draw still needs to be claimed */
SendToICS(ics_prefix);
SendToICS("draw\n");
} else if (StrCaseStr(resultDetails, "resign")) {
SendToICS(ics_prefix);
SendToICS("resign\n");
}
}
#endif
endingGame = 0; /* [HGM] crash */
return;
}
/* If we're loading the game from a file, stop */
if (whosays == GE_FILE) {
(void) StopLoadGameTimer();
gameFileFP = NULL;
}
/* Cancel draw offers */
first.offeredDraw = second.offeredDraw = 0;
/* If this is an ICS game, only ICS can really say it's done;
if not, anyone can. */
isIcsGame = (gameMode == IcsPlayingWhite ||
gameMode == IcsPlayingBlack ||
gameMode == IcsObserving ||
gameMode == IcsExamining);
if (!isIcsGame || whosays == GE_ICS) {
/* OK -- not an ICS game, or ICS said it was done */
StopClocks();
if (!isIcsGame && !appData.noChessProgram)
SetUserThinkingEnables();
/* [HGM] if a machine claims the game end we verify this claim */
if(gameMode == TwoMachinesPlay && appData.testClaims) {
if(appData.testLegality && whosays >= GE_ENGINE1 ) {
char claimer;
ChessMove trueResult = (ChessMove) -1;
claimer = whosays == GE_ENGINE1 ? /* color of claimer */
first.twoMachinesColor[0] :
second.twoMachinesColor[0] ;
// [HGM] losers: because the logic is becoming a bit hairy, determine true result first
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
/* [HGM] verify: engine mate claims accepted if they were flagged */
trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
} else
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
/* [HGM] verify: engine mate claims accepted if they were flagged */
trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
} else
if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
}
// now verify win claims, but not in drop games, as we don't understand those yet
if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
|| gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
(result == WhiteWins && claimer == 'w' ||
result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
if (appData.debugMode) {
fprintf(debugFP, "result=%d sp=%d move=%d\n",
result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
}
if(result != trueResult) {
snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
result = claimer == 'w' ? BlackWins : WhiteWins;
resultDetails = buf;
}
} else
if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
&& (forwardMostMove <= backwardMostMove ||
(signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
(claimer=='b')==(forwardMostMove&1))
) {
/* [HGM] verify: draws that were not flagged are false claims */
snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
result = claimer == 'w' ? BlackWins : WhiteWins;
resultDetails = buf;
}
/* (Claiming a loss is accepted no questions asked!) */
} else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
result = GameUnfinished;
if(!*appData.tourneyFile) matchGame--; // replay even in plain match
}
/* [HGM] bare: don't allow bare King to win */
if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
|| gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
&& gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
&& gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
&& result != GameIsDrawn)
{ int i, j, k=0, oppoKings = 0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
int p = (int)boards[forwardMostMove][i][j] - color;
if(p >= 0 && p <= (int)WhiteKing) k++;
oppoKings += (p + color == WhiteKing + BlackPawn - color);
}
if (appData.debugMode) {
fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
result, resultDetails ? resultDetails : "(null)", whosays, k, color);
}
if(k <= 1 && oppoKings > 0) { // the latter needed in Atomic, where bare K wins if opponent King already destroyed
result = GameIsDrawn;
snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
resultDetails = buf;
}
}
}
if(serverMoves != NULL && !loadFlag) { char c = '=';
if(result==WhiteWins) c = '+';
if(result==BlackWins) c = '-';
if(resultDetails != NULL)
fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
}
if (resultDetails != NULL) {
gameInfo.result = result;
gameInfo.resultDetails = StrSave(resultDetails);
/* display last move only if game was not loaded from file */
if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
DisplayMove(currentMove - 1);
if (forwardMostMove != 0) {
if (gameMode != PlayFromGameFile && gameMode != EditGame
&& lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
) {
if (*appData.saveGameFile != NULLCHAR) {
if(result == GameUnfinished && matchMode && *appData.tourneyFile)
AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
else
SaveGameToFile(appData.saveGameFile, TRUE);
} else if (appData.autoSaveGames) {
if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
}
if (*appData.savePositionFile != NULLCHAR) {
SavePositionToFile(appData.savePositionFile);
}
AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
}
}
/* Tell program how game ended in case it is learning */
/* [HGM] Moved this to after saving the PGN, just in case */
/* engine died and we got here through time loss. In that */
/* case we will get a fatal error writing the pipe, which */
/* would otherwise lose us the PGN. */
/* [HGM] crash: not needed anymore, but doesn't hurt; */
/* output during GameEnds should never be fatal anymore */
if (gameMode == MachinePlaysWhite ||
gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay ||
gameMode == IcsPlayingWhite ||
gameMode == IcsPlayingBlack ||
gameMode == BeginningOfGame) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
resultDetails);
if (first.pr != NoProc) {
SendToProgram(buf, &first);
}
if (second.pr != NoProc &&
gameMode == TwoMachinesPlay) {
SendToProgram(buf, &second);
}
}
}
if (appData.icsActive) {
if (appData.quietPlay &&
(gameMode == IcsPlayingWhite ||
gameMode == IcsPlayingBlack)) {
SendToICS(ics_prefix);
SendToICS("set shout 1\n");
}
nextGameMode = IcsIdle;
ics_user_moved = FALSE;
/* clean up premove. It's ugly when the game has ended and the
* premove highlights are still on the board.
*/
if (gotPremove) {
gotPremove = FALSE;
ClearPremoveHighlights();
DrawPosition(FALSE, boards[currentMove]);
}
if (whosays == GE_ICS) {
switch (result) {
case WhiteWins:
if (gameMode == IcsPlayingWhite)
PlayIcsWinSound();
else if(gameMode == IcsPlayingBlack)
PlayIcsLossSound();
break;
case BlackWins:
if (gameMode == IcsPlayingBlack)
PlayIcsWinSound();
else if(gameMode == IcsPlayingWhite)
PlayIcsLossSound();
break;
case GameIsDrawn:
PlayIcsDrawSound();
break;
default:
PlayIcsUnfinishedSound();
}
}
if(appData.quitNext) { ExitEvent(0); return; }
} else if (gameMode == EditGame ||
gameMode == PlayFromGameFile ||
gameMode == AnalyzeMode ||
gameMode == AnalyzeFile) {
nextGameMode = gameMode;
} else {
nextGameMode = EndOfGame;
}
pausing = FALSE;
ModeHighlight();
} else {
nextGameMode = gameMode;
}
if (appData.noChessProgram) {
gameMode = nextGameMode;
ModeHighlight();
endingGame = 0; /* [HGM] crash */
return;
}
if (first.reuse) {
/* Put first chess program into idle state */
if (first.pr != NoProc &&
(gameMode == MachinePlaysWhite ||
gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay ||
gameMode == IcsPlayingWhite ||
gameMode == IcsPlayingBlack ||
gameMode == BeginningOfGame)) {
SendToProgram("force\n", &first);
if (first.usePing) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
SendToProgram(buf, &first);
}
}
} else if (result != GameUnfinished || nextGameMode == IcsIdle) {
/* Kill off first chess program */
if (first.isr != NULL)
RemoveInputSource(first.isr);
first.isr = NULL;
if (first.pr != NoProc) {
ExitAnalyzeMode();
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", &first);
DestroyChildProcess(first.pr, 4 + first.useSigterm);
first.reload = TRUE;
}
first.pr = NoProc;
}
if (second.reuse) {
/* Put second chess program into idle state */
if (second.pr != NoProc &&
gameMode == TwoMachinesPlay) {
SendToProgram("force\n", &second);
if (second.usePing) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
SendToProgram(buf, &second);
}
}
} else if (result != GameUnfinished || nextGameMode == IcsIdle) {
/* Kill off second chess program */
if (second.isr != NULL)
RemoveInputSource(second.isr);
second.isr = NULL;
if (second.pr != NoProc) {
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", &second);
DestroyChildProcess(second.pr, 4 + second.useSigterm);
second.reload = TRUE;
}
second.pr = NoProc;
}
if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
char resChar = '=';
switch (result) {
case WhiteWins:
resChar = '+';
if (first.twoMachinesColor[0] == 'w') {
first.matchWins++;
} else {
second.matchWins++;
}
break;
case BlackWins:
resChar = '-';
if (first.twoMachinesColor[0] == 'b') {
first.matchWins++;
} else {
second.matchWins++;
}
break;
case GameUnfinished:
resChar = ' ';
default:
break;
}
if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
ReserveGame(nextGame, resChar); // sets nextGame
if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
else ranking = strdup("busy"); //suppress popup when aborted but not finished
} else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
if (nextGame <= appData.matchGames && !abortMatch) {
gameMode = nextGameMode;
matchGame = nextGame; // this will be overruled in tourney mode!
GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
endingGame = 0; /* [HGM] crash */
return;
} else {
gameMode = nextGameMode;
if(appData.epd) {
snprintf(buf, MSG_SIZ, "-------------------------------------- ");
OutputKibitz(2, buf);
snprintf(buf, MSG_SIZ, _("Average solving time %4.2f sec (total time %4.2f sec) "), totalTime/(100.*first.matchWins), totalTime/100.);
OutputKibitz(2, buf);
snprintf(buf, MSG_SIZ, _("%d avoid-moves played "), second.matchWins);
if(second.matchWins) OutputKibitz(2, buf);
snprintf(buf, MSG_SIZ, _("Solved %d out of %d (%3.1f%%) "), first.matchWins, nextGame-1, first.matchWins*100./(nextGame-1));
OutputKibitz(2, buf);
}
snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
first.tidy, second.tidy,
first.matchWins, second.matchWins,
appData.matchGames - (first.matchWins + second.matchWins));
if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
popupRequested++; // [HGM] crash: postpone to after resetting endingGame
if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
first.twoMachinesColor = "black\n";
second.twoMachinesColor = "white\n";
} else {
first.twoMachinesColor = "white\n";
second.twoMachinesColor = "black\n";
}
}
}
if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
!(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
ExitAnalyzeMode();
gameMode = nextGameMode;
ModeHighlight();
endingGame = 0; /* [HGM] crash */
if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
if(matchMode == TRUE) { // match through command line: exit with or without popup
if(ranking) {
ToNrEvent(forwardMostMove);
if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
else ExitEvent(0);
} else DisplayFatalError(buf, 0, 0);
} else { // match through menu; just stop, with or without popup
matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
ModeHighlight();
if(ranking){
if(strcmp(ranking, "busy")) DisplayNote(ranking);
} else DisplayNote(buf);
}
if(ranking) free(ranking);
}
}
/* Assumes program was just initialized (initString sent).
Leaves program in force mode. */
void
FeedMovesToProgram (ChessProgramState *cps, int upto)
{
int i;
if (appData.debugMode)
fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
startedFromSetupPosition ? "position and " : "",
backwardMostMove, upto, cps->which);
if(currentlyInitializedVariant != gameInfo.variant) {
char buf[MSG_SIZ];
// [HGM] variantswitch: make engine aware of new variant
if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
SendToProgram(buf, cps);
currentlyInitializedVariant = gameInfo.variant;
}
SendToProgram("force\n", cps);
if (startedFromSetupPosition) {
SendBoard(cps, backwardMostMove);
if (appData.debugMode) {
fprintf(debugFP, "feedMoves\n");
}
}
for (i = backwardMostMove; i < upto; i++) {
SendMoveToProgram(i, cps);
}
}
int
ResurrectChessProgram ()
{
/* The chess program may have exited.
If so, restart it and feed it all the moves made so far. */
static int doInit = 0;
if (appData.noChessProgram) return 1;
if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
} else {
if (first.pr != NoProc) return 1;
StartChessProgram(&first);
}
InitChessProgram(&first, FALSE);
FeedMovesToProgram(&first, currentMove);
if (!first.sendTime) {
/* can't tell gnuchess what its clock should read,
so we bow to its notion. */
ResetClocks();
timeRemaining[0][currentMove] = whiteTimeRemaining;
timeRemaining[1][currentMove] = blackTimeRemaining;
}
if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
appData.icsEngineAnalyze) && first.analysisSupport) {
SendToProgram("analyze\n", &first);
first.analyzing = TRUE;
}
return 1;
}
/*
* Button procedures
*/
void
Reset (int redraw, int init)
{
int i;
if (appData.debugMode) {
fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
redraw, init, gameMode);
}
pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
deadRanks = 0; // assume entire board is used
for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
CleanupTail(); // [HGM] vari: delete any stored variations
CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
pausing = pauseExamInvalid = FALSE;
startedFromSetupPosition = blackPlaysFirst = FALSE;
firstMove = TRUE;
whiteFlag = blackFlag = FALSE;
userOfferedDraw = FALSE;
hintRequested = bookRequested = FALSE;
first.maybeThinking = FALSE;
second.maybeThinking = FALSE;
first.bookSuspend = FALSE; // [HGM] book
second.bookSuspend = FALSE;
thinkOutput[0] = NULLCHAR;
lastHint[0] = NULLCHAR;
ClearGameInfo(&gameInfo);
gameInfo.variant = StringToVariant(appData.variant);
if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) {
gameInfo.variant = VariantUnknown;
strncpy(engineVariant, appData.variant, MSG_SIZ);
}
ics_user_moved = ics_clock_paused = FALSE;
ics_getting_history = H_FALSE;
ics_gamenum = -1;
white_holding[0] = black_holding[0] = NULLCHAR;
ClearProgramStats();
opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
ResetFrontEnd();
ClearHighlights();
flipView = appData.flipView;
ClearPremoveHighlights();
gotPremove = FALSE;
alarmSounded = FALSE;
killX = killY = kill2X = kill2Y = -1; // [HGM] lion
GameEnds(EndOfFile, NULL, GE_PLAYER);
if(appData.serverMovesName != NULL) {
/* [HGM] prepare to make moves file for broadcasting */
clock_t t = clock();
if(serverMoves != NULL) fclose(serverMoves);
serverMoves = fopen(appData.serverMovesName, "r");
if(serverMoves != NULL) {
fclose(serverMoves);
/* delay 15 sec before overwriting, so all clients can see end */
while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
}
serverMoves = fopen(appData.serverMovesName, "w");
}
ExitAnalyzeMode();
gameMode = BeginningOfGame;
ModeHighlight();
if(appData.icsActive) gameInfo.variant = VariantNormal;
currentMove = forwardMostMove = backwardMostMove = 0;
MarkTargetSquares(1);
InitPosition(redraw);
for (i = 0; i < MAX_MOVES; i++) {
if (commentList[i] != NULL) {
free(commentList[i]);
commentList[i] = NULL;
}
}
ResetClocks();
timeRemaining[0][0] = whiteTimeRemaining;
timeRemaining[1][0] = blackTimeRemaining;
if (first.pr == NoProc) {
StartChessProgram(&first);
}
if (init) {
InitChessProgram(&first, startedFromSetupPosition);
}
DisplayTitle("");
DisplayMessage("", "");
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
ClearMap(); // [HGM] exclude: invalidate map
}
void
AutoPlayGameLoop ()
{
for (;;) {
if (!AutoPlayOneMove())
return;
if (matchMode || appData.timeDelay == 0)
continue;
if (appData.timeDelay < 0)
return;
StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
break;
}
}
void
AnalyzeNextGame()
{
ReloadGame(1); // next game
}
int
AutoPlayOneMove ()
{
int fromX, fromY, toX, toY;
if (appData.debugMode) {
fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
}
if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
return FALSE;
if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
pvInfoList[currentMove].depth = programStats.depth;
pvInfoList[currentMove].score = programStats.score;
pvInfoList[currentMove].time = 0;
if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
else { // append analysis of final position as comment
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
}
programStats.depth = 0;
}
if (currentMove >= forwardMostMove) {
if(gameMode == AnalyzeFile) {
if(appData.loadGameIndex == -1) {
GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
ScheduleDelayedEvent(AnalyzeNextGame, 10);
} else {
ExitAnalyzeMode(); SendToProgram("force\n", &first);
}
}
// gameMode = EndOfGame;
// ModeHighlight();
/* [AS] Clear current move marker at the end of a game */
/* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
return FALSE;
}
toX = moveList[currentMove][2] - AAA;
toY = moveList[currentMove][3] - ONE;
if (moveList[currentMove][1] == '@') {
if (appData.highlightLastMove) {
SetHighlights(-1, -1, toX, toY);
}
} else {
fromX = moveList[currentMove][0] - AAA;
fromY = moveList[currentMove][1] - ONE;
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
if(moveList[currentMove][4] == ';') { // multi-leg
killX = moveList[currentMove][5] - AAA;
killY = moveList[currentMove][6] - ONE;
}
AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
killX = killY = -1;
if (appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
}
}
DisplayMove(currentMove);
SendMoveToProgram(currentMove++, &first);
DisplayBothClocks();
DrawPosition(FALSE, boards[currentMove]);
// [HGM] PV info: always display, routine tests if empty
DisplayComment(currentMove - 1, commentList[currentMove]);
return TRUE;
}
int
LoadGameOneMove (ChessMove readAhead)
{
int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
char promoChar = NULLCHAR;
ChessMove moveType;
char move[MSG_SIZ];
char *p, *q;
if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
gameMode != AnalyzeMode && gameMode != Training) {
gameFileFP = NULL;
return FALSE;
}
yyboardindex = forwardMostMove;
if (readAhead != EndOfFile) {
moveType = readAhead;
} else {
if (gameFileFP == NULL)
return FALSE;
moveType = (ChessMove) Myylex();
}
done = FALSE;
switch (moveType) {
case Comment:
if (appData.debugMode)
fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
p = yy_text;
/* append the comment but don't display it */
AppendComment(currentMove, p, FALSE);
return TRUE;
case WhiteCapturesEnPassant:
case BlackCapturesEnPassant:
case WhitePromotion:
case BlackPromotion:
case WhiteNonPromotion:
case BlackNonPromotion:
case NormalMove:
case FirstLeg:
case WhiteKingSideCastle:
case WhiteQueenSideCastle:
case BlackKingSideCastle:
case BlackQueenSideCastle:
case WhiteKingSideCastleWild:
case WhiteQueenSideCastleWild:
case BlackKingSideCastleWild:
case BlackQueenSideCastleWild:
/* PUSH Fabien */
case WhiteHSideCastleFR:
case WhiteASideCastleFR:
case BlackHSideCastleFR:
case BlackASideCastleFR:
/* POP Fabien */
if (appData.debugMode)
fprintf(debugFP, "Parsed %s into %s virgin=%x,%x\n", yy_text, currentMoveString, boards[forwardMostMove][TOUCHED_W], boards[forwardMostMove][TOUCHED_B]);
fromX = currentMoveString[0] - AAA;
fromY = currentMoveString[1] - ONE;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = currentMoveString[4];
if(promoChar == ';') promoChar = currentMoveString[7];
break;
case WhiteDrop:
case BlackDrop:
if (appData.debugMode)
fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
fromX = moveType == WhiteDrop ?
(int) CharToPiece(ToUpper(currentMoveString[0])) :
(int) CharToPiece(ToLower(currentMoveString[0]));
fromY = DROP_RANK;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
break;
case WhiteWins:
case BlackWins:
case GameIsDrawn:
case GameUnfinished:
if (appData.debugMode)
fprintf(debugFP, "Parsed game end: %s\n", yy_text);
p = strchr(yy_text, '{');
if (p == NULL) p = strchr(yy_text, '(');
if (p == NULL) {
p = yy_text;
if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
} else {
q = strchr(p, *p == '{' ? '}' : ')');
if (q != NULL) *q = NULLCHAR;
p++;
}
while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
GameEnds(moveType, p, GE_FILE);
done = TRUE;
if (cmailMsgLoaded) {
ClearHighlights();
flipView = WhiteOnMove(currentMove);
if (moveType == GameUnfinished) flipView = !flipView;
if (appData.debugMode)
fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
}
break;
case EndOfFile:
if (appData.debugMode)
fprintf(debugFP, "Parser hit end of file\n");
switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
case MT_NONE:
case MT_CHECK:
break;
case MT_CHECKMATE:
case MT_STAINMATE:
if (WhiteOnMove(currentMove)) {
GameEnds(BlackWins, "Black mates", GE_FILE);
} else {
GameEnds(WhiteWins, "White mates", GE_FILE);
}
break;
case MT_STALEMATE:
GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
break;
}
done = TRUE;
break;
case MoveNumberOne:
if (lastLoadGameStart == GNUChessGame) {
/* GNUChessGames have numbers, but they aren't move numbers */
if (appData.debugMode)
fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
yy_text, (int) moveType);
return LoadGameOneMove(EndOfFile); /* tail recursion */
}
/* else fall thru */
case XBoardGame:
case GNUChessGame:
case PGNTag:
/* Reached start of next game in file */
if (appData.debugMode)
fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
case MT_NONE:
case MT_CHECK:
break;
case MT_CHECKMATE:
case MT_STAINMATE:
if (WhiteOnMove(currentMove)) {
GameEnds(BlackWins, "Black mates", GE_FILE);
} else {
GameEnds(WhiteWins, "White mates", GE_FILE);
}
break;
case MT_STALEMATE:
GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
break;
}
done = TRUE;
break;
case PositionDiagram: /* should not happen; ignore */
case ElapsedTime: /* ignore */
case NAG: /* ignore */
if (appData.debugMode)
fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
yy_text, (int) moveType);
return LoadGameOneMove(EndOfFile); /* tail recursion */
case IllegalMove:
if (appData.testLegality) {
if (appData.debugMode)
fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
(forwardMostMove / 2) + 1,
WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
DisplayError(move, 0);
done = TRUE;
} else {
if (appData.debugMode)
fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
yy_text, currentMoveString);
if(currentMoveString[1] == '@') {
fromX = CharToPiece(WhiteOnMove(currentMove) ? ToUpper(currentMoveString[0]) : ToLower(currentMoveString[0]));
fromY = DROP_RANK;
} else {
fromX = currentMoveString[0] - AAA;
fromY = currentMoveString[1] - ONE;
}
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = currentMoveString[4];
}
break;
case AmbiguousMove:
if (appData.debugMode)
fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
(forwardMostMove / 2) + 1,
WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
DisplayError(move, 0);
done = TRUE;
break;
default:
case ImpossibleMove:
if (appData.debugMode)
fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
(forwardMostMove / 2) + 1,
WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
DisplayError(move, 0);
done = TRUE;
break;
}
if (done) {
if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
DrawPosition(FALSE, boards[currentMove]);
DisplayBothClocks();
if (!appData.matchMode) // [HGM] PV info: routine tests if empty
DisplayComment(currentMove - 1, commentList[currentMove]);
}
(void) StopLoadGameTimer();
gameFileFP = NULL;
cmailOldMove = forwardMostMove;
return FALSE;
} else {
/* currentMoveString is set as a side-effect of yylex */
thinkOutput[0] = NULLCHAR;
MakeMove(fromX, fromY, toX, toY, promoChar);
killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
currentMove = forwardMostMove;
return TRUE;
}
}
/* Load the nth game from the given file */
int
LoadGameFromFile (char *filename, int n, char *title, int useList)
{
FILE *f;
char buf[MSG_SIZ];
if (strcmp(filename, "-") == 0) {
f = stdin;
title = "stdin";
} else {
f = fopen(filename, "rb");
if (f == NULL) {
snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
DisplayError(buf, errno);
return FALSE;
}
}
if (fseek(f, 0, 0) == -1) {
/* f is not seekable; probably a pipe */
useList = FALSE;
}
if (useList && n == 0) {
int error = GameListBuild(f);
if (error) {
DisplayError(_("Cannot build game list"), error);
} else if (!ListEmpty(&gameList) &&
((ListGame *) gameList.tailPred)->number > 1) {
GameListPopUp(f, title);
return TRUE;
}
GameListDestroy();
n = 1;
}
if (n == 0) n = 1;
return LoadGame(f, n, title, FALSE);
}
void
MakeRegisteredMove ()
{
int fromX, fromY, toX, toY;
char promoChar;
if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
switch (cmailMoveType[lastLoadGameNumber - 1]) {
case CMAIL_MOVE:
case CMAIL_DRAW:
if (appData.debugMode)
fprintf(debugFP, "Restoring %s for game %d\n",
cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
thinkOutput[0] = NULLCHAR;
safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
promoChar = cmailMove[lastLoadGameNumber - 1][4];
MakeMove(fromX, fromY, toX, toY, promoChar);
ShowMove(fromX, fromY, toX, toY);
switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
case MT_NONE:
case MT_CHECK:
break;
case MT_CHECKMATE:
case MT_STAINMATE:
if (WhiteOnMove(currentMove)) {
GameEnds(BlackWins, "Black mates", GE_PLAYER);
} else {
GameEnds(WhiteWins, "White mates", GE_PLAYER);
}
break;
case MT_STALEMATE:
GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
break;
}
break;
case CMAIL_RESIGN:
if (WhiteOnMove(currentMove)) {
GameEnds(BlackWins, "White resigns", GE_PLAYER);
} else {
GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
}
break;
case CMAIL_ACCEPT:
GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
break;
default:
break;
}
}
return;
}
/* Wrapper around LoadGame for use when a Cmail message is loaded */
int
CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
{
int retVal;
if (gameNumber > nCmailGames) {
DisplayError(_("No more games in this message"), 0);
return FALSE;
}
if (f == lastLoadGameFP) {
int offset = gameNumber - lastLoadGameNumber;
if (offset == 0) {
cmailMsg[0] = NULLCHAR;
if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
nCmailMovesRegistered--;
}
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
}
} else {
if (! RegisterMove()) return FALSE;
}
}
retVal = LoadGame(f, gameNumber, title, useList);
/* Make move registered during previous look at this game, if any */
MakeRegisteredMove();
if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
commentList[currentMove]
= StrSave(cmailCommentList[lastLoadGameNumber - 1]);
DisplayComment(currentMove - 1, commentList[currentMove]);
}
return retVal;
}
/* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
int
ReloadGame (int offset)
{
int gameNumber = lastLoadGameNumber + offset;
if (lastLoadGameFP == NULL) {
DisplayError(_("No game has been loaded yet"), 0);
return FALSE;
}
if (gameNumber <= 0) {
DisplayError(_("Can't back up any further"), 0);
return FALSE;
}
if (cmailMsgLoaded) {
return CmailLoadGame(lastLoadGameFP, gameNumber,
lastLoadGameTitle, lastLoadGameUseList);
} else {
return LoadGame(lastLoadGameFP, gameNumber,
lastLoadGameTitle, lastLoadGameUseList);
}
}
int keys[EmptySquare+1];
int
PositionMatches (Board b1, Board b2)
{
int r, f, sum=0;
switch(appData.searchMode) {
case 1: return CompareWithRights(b1, b2);
case 2:
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
}
return TRUE;
case 3:
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
sum += keys[b1[r][f]] - keys[b2[r][f]];
}
return sum==0;
case 4:
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
sum += keys[b1[r][f]] - keys[b2[r][f]];
}
return sum==0;
}
return TRUE;
}
#define Q_PROMO 4
#define Q_EP 3
#define Q_BCASTL 2
#define Q_WCASTL 1
int pieceList[256], quickBoard[256];
ChessSquare pieceType[256] = { EmptySquare };
Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
int soughtTotal, turn;
Boolean epOK, flipSearch;
typedef struct {
unsigned char piece, to;
} Move;
#define DSIZE (250000)
Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
Move *moveDatabase = initialSpace;
unsigned int movePtr, dataSize = DSIZE;
int
MakePieceList (Board board, int *counts)
{
int r, f, n=Q_PROMO, total=0;
for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
int sq = f + (r<<4);
if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
quickBoard[sq] = ++n;
pieceList[n] = sq;
pieceType[n] = board[r][f];
counts[board[r][f]]++;
if(board[r][f] == WhiteKing) pieceList[1] = n; else
if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
total++;
}
}
epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
return total;
}
void
PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
{
int sq = fromX + (fromY<<4);
int piece = quickBoard[sq], rook;
quickBoard[sq] = 0;
moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
if(piece == pieceList[1] && fromY == toY) {
if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
moveDatabase[movePtr++].piece = Q_WCASTL;
quickBoard[sq] = piece;
piece = quickBoard[from]; quickBoard[from] = 0;
moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
} else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
quickBoard[sq] = 0; // remove Rook
moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
moveDatabase[movePtr++].piece = Q_WCASTL;
quickBoard[sq] = pieceList[1]; // put King
piece = rook;
moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
}
} else
if(piece == pieceList[2] && fromY == toY) {
if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
moveDatabase[movePtr++].piece = Q_BCASTL;
quickBoard[sq] = piece;
piece = quickBoard[from]; quickBoard[from] = 0;
moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
} else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
quickBoard[sq] = 0; // remove Rook
moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
moveDatabase[movePtr++].piece = Q_BCASTL;
quickBoard[sq] = pieceList[2]; // put King
piece = rook;
moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
}
} else
if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
quickBoard[(fromY<<4)+toX] = 0;
moveDatabase[movePtr].piece = Q_EP;
moveDatabase[movePtr++].to = (fromY<<4)+toX;
moveDatabase[movePtr].to = sq;
} else
if(promoPiece != pieceType[piece]) {
moveDatabase[movePtr++].piece = Q_PROMO;
moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
}
moveDatabase[movePtr].piece = piece;
quickBoard[sq] = piece;
movePtr++;
}
int
PackGame (Board board)
{
Move *newSpace = NULL;
moveDatabase[movePtr].piece = 0; // terminate previous game
if(movePtr > dataSize) {
if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
if(newSpace) {
int i;
Move *p = moveDatabase, *q = newSpace;
for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
moveDatabase = newSpace;
} else { // calloc failed, we must be out of memory. Too bad...
dataSize = 0; // prevent calloc events for all subsequent games
return 0; // and signal this one isn't cached
}
}
movePtr++;
MakePieceList(board, counts);
return movePtr;
}
int
QuickCompare (Board board, int *minCounts, int *maxCounts)
{ // compare according to search mode
int r, f;
switch(appData.searchMode)
{
case 1: // exact position match
if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
}
break;
case 2: // can have extra material on empty squares
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
if(board[r][f] == EmptySquare) continue;
if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
}
break;
case 3: // material with exact Pawn structure
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
} // fall through to material comparison
case 4: // exact material
for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
break;
case 6: // material range with given imbalance
for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
// fall through to range comparison
case 5: // material range
for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
}
return TRUE;
}
int
QuickScan (Board board, Move *move)
{ // reconstruct game,and compare all positions in it
int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
do {
int piece = move->piece;
int to = move->to, from = pieceList[piece];
if(found < 0) { // if already found just scan to game end for final piece count
if(QuickCompare(soughtBoard, minSought, maxSought) ||
appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
) {
static int lastCounts[EmptySquare+1];
int i;
if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
} else stretch = 0;
if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
if(found >= 0 && !appData.minPieces) return found;
}
if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
piece = (++move)->piece;
from = pieceList[piece];
counts[pieceType[piece]]--;
pieceType[piece] = (ChessSquare) move->to;
counts[move->to]++;
} else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
counts[pieceType[quickBoard[to]]]--;
quickBoard[to] = 0; total--;
move++;
continue;
} else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
piece = pieceList[piece]; // first two elements of pieceList contain King numbers
from = pieceList[piece]; // so this must be King
quickBoard[from] = 0;
pieceList[piece] = to;
from = pieceList[(++move)->piece]; // for FRC this has to be done here
quickBoard[from] = 0; // rook
quickBoard[to] = piece;
to = move->to; piece = move->piece;
goto aftercastle;
}
}
if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
quickBoard[from] = 0;
aftercastle:
quickBoard[to] = piece;
pieceList[piece] = to;
cnt++; turn ^= 3;
move++;
} while(1);
}
void
InitSearch ()
{
int r, f;
flipSearch = FALSE;
CopyBoard(soughtBoard, boards[currentMove]);
soughtTotal = MakePieceList(soughtBoard, maxSought);
soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
CopyBoard(reverseBoard, boards[currentMove]);
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
reverseBoard[r][f] = piece;
}
reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
|| (boards[currentMove][CASTLING][2] == NoRights ||
boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
&& (boards[currentMove][CASTLING][5] == NoRights ||
boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
) {
flipSearch = TRUE;
CopyBoard(flipBoard, soughtBoard);
CopyBoard(rotateBoard, reverseBoard);
for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
}
}
for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
if(appData.searchMode >= 5) {
for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
MakePieceList(soughtBoard, minSought);
for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
}
if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
}
GameInfo dummyInfo;
static int creatingBook;
int
GameContainsPosition (FILE *f, ListGame *lg)
{
int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
int fromX, fromY, toX, toY;
char promoChar;
static int initDone=FALSE;
// weed out games based on numerical tag comparison
if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
if(!initDone) {
for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
initDone = TRUE;
}
if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
else CopyBoard(boards[scratch], initialPosition); // default start position
if(lg->moves) {
turn = btm + 1;
if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
}
if(btm) plyNr++;
if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
fseek(f, lg->offset, 0);
yynewfile(f);
while(1) {
yyboardindex = scratch;
quickFlag = plyNr+1;
next = Myylex();
quickFlag = 0;
switch(next) {
case PGNTag:
if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
default:
continue;
case XBoardGame:
case GNUChessGame:
if(plyNr) return -1; // after we have seen moves, this is for new game
continue;
case AmbiguousMove: // we cannot reconstruct the game beyond these two
case ImpossibleMove:
case WhiteWins: // game ends here with these four
case BlackWins:
case GameIsDrawn:
case GameUnfinished:
return -1;
case IllegalMove:
if(appData.testLegality) return -1;
case WhiteCapturesEnPassant:
case BlackCapturesEnPassant:
case WhitePromotion:
case BlackPromotion:
case WhiteNonPromotion:
case BlackNonPromotion:
case NormalMove:
case FirstLeg:
case WhiteKingSideCastle:
case WhiteQueenSideCastle:
case BlackKingSideCastle:
case BlackQueenSideCastle:
case WhiteKingSideCastleWild:
case WhiteQueenSideCastleWild:
case BlackKingSideCastleWild:
case BlackQueenSideCastleWild:
case WhiteHSideCastleFR:
case WhiteASideCastleFR:
case BlackHSideCastleFR:
case BlackASideCastleFR:
fromX = currentMoveString[0] - AAA;
fromY = currentMoveString[1] - ONE;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = currentMoveString[4];
break;
case WhiteDrop:
case BlackDrop:
fromX = next == WhiteDrop ?
(int) CharToPiece(ToUpper(currentMoveString[0])) :
(int) CharToPiece(ToLower(currentMoveString[0]));
fromY = DROP_RANK;
toX = currentMoveString[2] - AAA;
toY = currentMoveString[3] - ONE;
promoChar = 0;
break;
}
// Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
plyNr++;
ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
if(appData.findMirror) {
if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
}
}
}
/* Load the nth game from open file f */
int
LoadGame (FILE *f, int gameNumber, char *title, int useList)
{
ChessMove cm;
char buf[MSG_SIZ];
int gn = gameNumber;
ListGame *lg = NULL;
int numPGNTags = 0, i;
int err, pos = -1;
GameMode oldGameMode;
VariantClass v, oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
char oldName[MSG_SIZ];
safeStrCpy(oldName, engineVariant, MSG_SIZ); v = oldVariant;
if (appData.debugMode)
fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
if (gameMode == Training )
SetTrainingModeOff();
oldGameMode = gameMode;
if (gameMode != BeginningOfGame) {
Reset(FALSE, TRUE);
}
killX = killY = kill2X = kill2Y = -1; // [HGM] lion: in case we did not Reset
gameFileFP = f;
if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
fclose(lastLoadGameFP);
}
if (useList) {
lg = (ListGame *) ListElem(&gameList, gameNumber-1);
if (lg) {
fseek(f, lg->offset, 0);
GameListHighlight(gameNumber);
pos = lg->position;
gn = 1;
}
else {
if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
else
DisplayError(_("Game number out of range"), 0);
return FALSE;
}
} else {
GameListDestroy();
if (fseek(f, 0, 0) == -1) {
if (f == lastLoadGameFP ?
gameNumber == lastLoadGameNumber + 1 :
gameNumber == 1) {
gn = 1;
} else {
DisplayError(_("Can't seek on game file"), 0);
return FALSE;
}
}
}
lastLoadGameFP = f;
lastLoadGameNumber = gameNumber;
safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
lastLoadGameUseList = useList;
yynewfile(f);
if (lg && lg->gameInfo.white && lg->gameInfo.black) {
snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
lg->gameInfo.black);
DisplayTitle(buf);
} else if (*title != NULLCHAR) {
if (gameNumber > 1) {
snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
DisplayTitle(buf);
} else {
DisplayTitle(title);
}
}
if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
gameMode = PlayFromGameFile;
ModeHighlight();
}
currentMove = forwardMostMove = backwardMostMove = 0;
CopyBoard(boards[0], initialPosition);
StopClocks();
/*
* Skip the first gn-1 games in the file.
* Also skip over anything that precedes an identifiable
* start of game marker, to avoid being confused by
* garbage at the start of the file. Currently
* recognized start of game markers are the move number "1",
* the pattern "gnuchess .* game", the pattern
* "^[#;%] [^ ]* game file", and a PGN tag block.
* A game that starts with one of the latter two patterns
* will also have a move number 1, possibly
* following a position diagram.
* 5-4-02: Let's try being more lenient and allowing a game to
* start with an unnumbered move. Does that break anything?
*/
cm = lastLoadGameStart = EndOfFile;
while (gn > 0) {
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
switch (cm) {
case EndOfFile:
if (cmailMsgLoaded) {
nCmailGames = CMAIL_MAX_GAMES - gn;
} else {
Reset(TRUE, TRUE);
DisplayError(_("Game not found in file"), 0);
}
return FALSE;
case GNUChessGame:
case XBoardGame:
gn--;
lastLoadGameStart = cm;
break;
case MoveNumberOne:
switch (lastLoadGameStart) {
case GNUChessGame:
case XBoardGame:
case PGNTag:
break;
case MoveNumberOne:
case EndOfFile:
gn--; /* count this game */
lastLoadGameStart = cm;
break;
default:
/* impossible */
break;
}
break;
case PGNTag:
switch (lastLoadGameStart) {
case GNUChessGame:
case PGNTag:
case MoveNumberOne:
case EndOfFile:
gn--; /* count this game */
lastLoadGameStart = cm;
break;
case XBoardGame:
lastLoadGameStart = cm; /* game counted already */
break;
default:
/* impossible */
break;
}
if (gn > 0) {
do {
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
} while (cm == PGNTag || cm == Comment);
}
break;
case WhiteWins:
case BlackWins:
case GameIsDrawn:
if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
!= CMAIL_OLD_RESULT) {
nCmailResults ++ ;
cmailResult[ CMAIL_MAX_GAMES
- gn - 1] = CMAIL_OLD_RESULT;
}
}
break;
case NormalMove:
case FirstLeg:
/* Only a NormalMove can be at the start of a game
* without a position diagram. */
if (lastLoadGameStart == EndOfFile ) {
gn--;
lastLoadGameStart = MoveNumberOne;
}
break;
default:
break;
}
}
if (appData.debugMode)
fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; } // reset VariantMen
if (cm == XBoardGame) {
/* Skip any header junk before position diagram and/or move 1 */
for (;;) {
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
if (cm == EndOfFile ||
cm == GNUChessGame || cm == XBoardGame) {
/* Empty game; pretend end-of-file and handle later */
cm = EndOfFile;
break;
}
if (cm == MoveNumberOne || cm == PositionDiagram ||
cm == PGNTag || cm == Comment)
break;
}
} else if (cm == GNUChessGame) {
if (gameInfo.event != NULL) {
free(gameInfo.event);
}
gameInfo.event = StrSave(yy_text);
}
startedFromSetupPosition = startedFromPositionFile; // [HGM]
while (cm == PGNTag) {
if (appData.debugMode)
fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
err = ParsePGNTag(yy_text, &gameInfo);
if (!err) numPGNTags++;
/* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
if(gameInfo.variant != oldVariant && (gameInfo.variant != VariantNormal || gameInfo.variantName == NULL || *gameInfo.variantName == NULLCHAR)) {
startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
InitPosition(TRUE);
oldVariant = gameInfo.variant;
if (appData.debugMode)
fprintf(debugFP, "New variant %d\n", (int) oldVariant);
}
if (gameInfo.fen != NULL) {
Board initial_position;
startedFromSetupPosition = TRUE;
if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
Reset(TRUE, TRUE);
DisplayError(_("Bad FEN position in file"), 0);
return FALSE;
}
CopyBoard(boards[0], initial_position);
if(*engineVariant || gameInfo.variant == VariantFairy) // [HGM] for now, assume FEN in engine-defined variant game is default initial position
CopyBoard(initialPosition, initial_position);
if (blackPlaysFirst) {
currentMove = forwardMostMove = backwardMostMove = 1;
CopyBoard(boards[1], initial_position);
safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
timeRemaining[0][1] = whiteTimeRemaining;
timeRemaining[1][1] = blackTimeRemaining;
if (commentList[0] != NULL) {
commentList[1] = commentList[0];
commentList[0] = NULL;
}
} else {
currentMove = forwardMostMove = backwardMostMove = 0;
}
/* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
{ int i;
initialRulePlies = FENrulePlies;
for( i=0; i< nrCastlingRights; i++ )
initialRights[i] = initial_position[CASTLING][i];
}
yyboardindex = forwardMostMove;
free(gameInfo.fen);
gameInfo.fen = NULL;
}
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
/* Handle comments interspersed among the tags */
while (cm == Comment) {
char *p;
if (appData.debugMode)
fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
p = yy_text;
AppendComment(currentMove, p, FALSE);
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
}
}
/* don't rely on existence of Event tag since if game was
* pasted from clipboard the Event tag may not exist
*/
if (numPGNTags > 0){
char *tags;
if (gameInfo.variant == VariantNormal) {
VariantClass v = StringToVariant(gameInfo.event);
// [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
if(v < VariantShogi) gameInfo.variant = v;
}
if (!matchMode) {
if( appData.autoDisplayTags ) {
tags = PGNTags(&gameInfo);
TagsPopUp(tags, CmailMsg());
free(tags);
}
}
} else {
/* Make something up, but don't display it now */
SetGameInfo();
TagsPopDown();
}
if (cm == PositionDiagram) {
int i, j;
char *p;
Board initial_position;
if (appData.debugMode)
fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
if (!startedFromSetupPosition) {
p = yy_text;
for (i = BOARD_HEIGHT - 1; i >= 0; i--)
for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
switch (*p) {
case '{':
case '[':
case '-':
case ' ':
case '\t':
case '\n':
case '\r':
break;
default:
initial_position[i][j++] = CharToPiece(*p);
break;
}
while (*p == ' ' || *p == '\t' ||
*p == '\n' || *p == '\r') p++;
if (strncmp(p, "black", strlen("black"))==0)
blackPlaysFirst = TRUE;
else
blackPlaysFirst = FALSE;
startedFromSetupPosition = TRUE;
CopyBoard(boards[0], initial_position);
if (blackPlaysFirst) {
currentMove = forwardMostMove = backwardMostMove = 1;
CopyBoard(boards[1], initial_position);
safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
timeRemaining[0][1] = whiteTimeRemaining;
timeRemaining[1][1] = blackTimeRemaining;
if (commentList[0] != NULL) {
commentList[1] = commentList[0];
commentList[0] = NULL;
}
} else {
currentMove = forwardMostMove = backwardMostMove = 0;
}
}
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
}
if(!creatingBook) {
if (first.pr == NoProc) {
StartChessProgram(&first);
}
InitChessProgram(&first, FALSE);
if(gameInfo.variant == VariantUnknown && *oldName) {
safeStrCpy(engineVariant, oldName, MSG_SIZ);
gameInfo.variant = v;
}
SendToProgram("force\n", &first);
if (startedFromSetupPosition) {
SendBoard(&first, forwardMostMove);
if (appData.debugMode) {
fprintf(debugFP, "Load Game\n");
}
DisplayBothClocks();
}
}
/* [HGM] server: flag to write setup moves in broadcast file as one */
loadFlag = appData.suppressLoadMoves;
while (cm == Comment) {
char *p;
if (appData.debugMode)
fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
p = yy_text;
AppendComment(currentMove, p, FALSE);
yyboardindex = forwardMostMove;
cm = (ChessMove) Myylex();
}
if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
cm == WhiteWins || cm == BlackWins ||
cm == GameIsDrawn || cm == GameUnfinished) {
DisplayMessage("", _("No moves in game"));
if (cmailMsgLoaded) {
if (appData.debugMode)
fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
ClearHighlights();
flipView = FALSE;
}
DrawPosition(FALSE, boards[currentMove]);
DisplayBothClocks();
gameMode = EditGame;
ModeHighlight();
gameFileFP = NULL;
cmailOldMove = 0;
return TRUE;
}
// [HGM] PV info: routine tests if comment empty
if (!matchMode && (pausing || appData.timeDelay != 0)) {
DisplayComment(currentMove - 1, commentList[currentMove]);
}
if (!matchMode && appData.timeDelay != 0)
DrawPosition(FALSE, boards[currentMove]);
if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
programStats.ok_to_send = 1;
}
/* if the first token after the PGN tags is a move
* and not move number 1, retrieve it from the parser
*/
if (cm != MoveNumberOne)
LoadGameOneMove(cm);
/* load the remaining moves from the file */
while (LoadGameOneMove(EndOfFile)) {
timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
timeRemaining[1][forwardMostMove] = blackTimeRemaining;
}
/* rewind to the start of the game */
currentMove = backwardMostMove;
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
if (oldGameMode == AnalyzeFile) {
appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
AnalyzeFileEvent();
} else
if (oldGameMode == AnalyzeMode) {
AnalyzeFileEvent();
}
if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
long int w, b; // [HGM] adjourn: restore saved clock times
char *p = strstr(gameInfo.resultDetails, "(Clocks:");
if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
}
}
if(creatingBook) return TRUE;
if (!matchMode && pos > 0) {
ToNrEvent(pos); // [HGM] no autoplay if selected on position
} else
if (matchMode || appData.timeDelay == 0) {
ToEndEvent();
} else if (appData.timeDelay > 0) {
AutoPlayGameLoop();
}
if (appData.debugMode)
fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
loadFlag = 0; /* [HGM] true game starts */
return TRUE;
}
/* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
int
ReloadPosition (int offset)
{
int positionNumber = lastLoadPositionNumber + offset;
if (lastLoadPositionFP == NULL) {
DisplayError(_("No position has been loaded yet"), 0);
return FALSE;
}
if (positionNumber <= 0) {
DisplayError(_("Can't back up any further"), 0);
return FALSE;
}
return LoadPosition(lastLoadPositionFP, positionNumber,
lastLoadPositionTitle);
}
/* Load the nth position from the given file */
int
LoadPositionFromFile (char *filename, int n, char *title)
{
FILE *f;
char buf[MSG_SIZ];
if (strcmp(filename, "-") == 0) {
return LoadPosition(stdin, n, "stdin");
} else {
f = fopen(filename, "rb");
if (f == NULL) {
snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
DisplayError(buf, errno);
return FALSE;
} else {
return LoadPosition(f, n, title);
}
}
}
/* Load the nth position from the given open file, and close it */
int
LoadPosition (FILE *f, int positionNumber, char *title)
{
char *p, line[MSG_SIZ];
Board initial_position;
int i, j, fenMode, pn;
if (gameMode == Training )
SetTrainingModeOff();
if (gameMode != BeginningOfGame) {
Reset(FALSE, TRUE);
}
if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
fclose(lastLoadPositionFP);
}
if (positionNumber == 0) positionNumber = 1;
lastLoadPositionFP = f;
lastLoadPositionNumber = positionNumber;
safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
if (first.pr == NoProc && !appData.noChessProgram) {
StartChessProgram(&first);
InitChessProgram(&first, FALSE);
}
pn = positionNumber;
if (positionNumber < 0) {
/* Negative position number means to seek to that byte offset */
if (fseek(f, -positionNumber, 0) == -1) {
DisplayError(_("Can't seek on position file"), 0);
return FALSE;
};
pn = 1;
} else {
if (fseek(f, 0, 0) == -1) {
if (f == lastLoadPositionFP ?
positionNumber == lastLoadPositionNumber + 1 :
positionNumber == 1) {
pn = 1;
} else {
DisplayError(_("Can't seek on position file"), 0);
return FALSE;
}
}
}
/* See if this file is FEN or old-style xboard */
if (fgets(line, MSG_SIZ, f) == NULL) {
DisplayError(_("Position not found in file"), 0);
return FALSE;
}
// [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces (or * for blackout)
fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || line[0] == '*' || CharToPiece(line[0]) != EmptySquare;
if (pn >= 2) {
if (fenMode || line[0] == '#') pn--;
while (pn > 0) {
/* skip positions before number pn */
if (fgets(line, MSG_SIZ, f) == NULL) {
Reset(TRUE, TRUE);
DisplayError(_("Position not found in file"), 0);
return FALSE;
}
if (fenMode || line[0] == '#') pn--;
}
}
if (fenMode) {
char *p;
if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
DisplayError(_("Bad FEN position in file"), 0);
return FALSE;
}
if((strchr(line, ';')) && (p = strstr(line, " bm "))) { // EPD with best move
sscanf(p+4, "%[^;]", bestMove);
} else *bestMove = NULLCHAR;
if((strchr(line, ';')) && (p = strstr(line, " am "))) { // EPD with avoid move
sscanf(p+4, "%[^;]", avoidMove);
} else *avoidMove = NULLCHAR;
} else {
(void) fgets(line, MSG_SIZ, f);
(void) fgets(line, MSG_SIZ, f);
for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
(void) fgets(line, MSG_SIZ, f);
for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
if (*p == ' ')
continue;
initial_position[i][j++] = CharToPiece(*p);
}
}
blackPlaysFirst = FALSE;
if (!feof(f)) {
(void) fgets(line, MSG_SIZ, f);
if (strncmp(line, "black", strlen("black"))==0)
blackPlaysFirst = TRUE;
}
}
startedFromSetupPosition = TRUE;
CopyBoard(boards[0], initial_position);
if (blackPlaysFirst) {
currentMove = forwardMostMove = backwardMostMove = 1;
safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
CopyBoard(boards[1], initial_position);
DisplayMessage("", _("Black to play"));
} else {
currentMove = forwardMostMove = backwardMostMove = 0;
DisplayMessage("", _("White to play"));
}
initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
SendToProgram("force\n", &first);
SendBoard(&first, forwardMostMove);
}
if (appData.debugMode) {
int i, j;
for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
fprintf(debugFP, "Load Position\n");
}
if (positionNumber > 1) {
snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
DisplayTitle(line);
} else {
DisplayTitle(title);
}
gameMode = EditGame;
ModeHighlight();
ResetClocks();
timeRemaining[0][1] = whiteTimeRemaining;
timeRemaining[1][1] = blackTimeRemaining;
DrawPosition(FALSE, boards[currentMove]);
return TRUE;
}
void
CopyPlayerNameIntoFileName (char **dest, char *src)
{
while (*src != NULLCHAR && *src != ',') {
if (*src == ' ') {
*(*dest)++ = '_';
src++;
} else {
*(*dest)++ = *src++;
}
}
}
char *
DefaultFileName (char *ext)
{
static char def[MSG_SIZ];
char *p;
if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
p = def;
CopyPlayerNameIntoFileName(&p, gameInfo.white);
*p++ = '-';
CopyPlayerNameIntoFileName(&p, gameInfo.black);
*p++ = '.';
safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
} else {
def[0] = NULLCHAR;
}
return def;
}
/* Save the current game to the given file */
int
SaveGameToFile (char *filename, int append)
{
FILE *f;
char buf[MSG_SIZ];
int result, i, t,tot=0;
if (strcmp(filename, "-") == 0) {
return SaveGame(stdout, 0, NULL);
} else {
for(i=0; i<10; i++) { // upto 10 tries
f = fopen(filename, append ? "a" : "w");
if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
if(f || errno != 13) break;
DoSleep(t = 5 + random()%11); // wait 5-15 msec
tot += t;
}
if (f == NULL) {
snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
DisplayError(buf, errno);
return FALSE;
} else {
safeStrCpy(buf, lastMsg, MSG_SIZ);
DisplayMessage(_("Waiting for access to save file"), "");
flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
DisplayMessage(_("Saving game"), "");
if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
result = SaveGame(f, 0, NULL);
DisplayMessage(buf, "");
return result;
}
}
}
char *
SavePart (char *str)
{
static char buf[MSG_SIZ];
char *p;
p = strchr(str, ' ');
if (p == NULL) return str;
strncpy(buf, str, p - str);
buf[p - str] = NULLCHAR;
return buf;
}
#define PGN_MAX_LINE 75
#define PGN_SIDE_WHITE 0
#define PGN_SIDE_BLACK 1
static int
FindFirstMoveOutOfBook (int side)
{
int result = -1;
if( backwardMostMove == 0 && ! startedFromSetupPosition) {
int index = backwardMostMove;
int has_book_hit = 0;
if( (index % 2) != side ) {
index++;
}
while( index < forwardMostMove ) {
/* Check to see if engine is in book */
int depth = pvInfoList[index].depth;
int score = pvInfoList[index].score;
int in_book = 0;
if( depth <= 2 ) {
in_book = 1;
}
else if( score == 0 && depth == 63 ) {
in_book = 1; /* Zappa */
}
else if( score == 2 && depth == 99 ) {
in_book = 1; /* Abrok */
}
has_book_hit += in_book;
if( ! in_book ) {
result = index;
break;
}
index += 2;
}
}
return result;
}
void
GetOutOfBookInfo (char * buf)
{
int oob[2];
int i;
int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
*buf = '\0';
if( oob[0] >= 0 || oob[1] >= 0 ) {
for( i=0; i<2; i++ ) {
int idx = oob[i];
if( idx >= 0 ) {
if( i > 0 && oob[0] >= 0 ) {
strcat( buf, " " );
}
sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
sprintf( buf+strlen(buf), "%s%.2f",
pvInfoList[idx].score >= 0 ? "+" : "",
pvInfoList[idx].score / 100.0 );
}
}
}
}
/* Save game in PGN style */
static void
SaveGamePGN2 (FILE *f)
{
int i, offset, linelen, newblock;
// char *movetext;
char numtext[32];
int movelen, numlen, blank;
char move_buffer[100]; /* [AS] Buffer for move+PV info */
offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
PrintPGNTags(f, &gameInfo);
if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
if (backwardMostMove > 0 || startedFromSetupPosition) {
char *fen = PositionToFEN(backwardMostMove, NULL, 1);
fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
fprintf(f, "\n{--------------\n");
PrintPosition(f, backwardMostMove);
fprintf(f, "--------------}\n");
free(fen);
}
else {
/* [AS] Out of book annotation */
if( appData.saveOutOfBookInfo ) {
char buf[64];
GetOutOfBookInfo( buf );
if( buf[0] != '\0' ) {
fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
}
}
fprintf(f, "\n");
}
i = backwardMostMove;
linelen = 0;
newblock = TRUE;
while (i < forwardMostMove) {
/* Print comments preceding this move */
if (commentList[i] != NULL) {
if (linelen > 0) fprintf(f, "\n");
fprintf(f, "%s", commentList[i]);
linelen = 0;
newblock = TRUE;
}
/* Format move number */
if ((i % 2) == 0)
snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
else
if (newblock)
snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
else
numtext[0] = NULLCHAR;
numlen = strlen(numtext);
newblock = FALSE;
/* Print move number */
blank = linelen > 0 && numlen > 0;
if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
fprintf(f, "\n");
linelen = 0;
blank = 0;
}
if (blank) {
fprintf(f, " ");
linelen++;
}
fprintf(f, "%s", numtext);
linelen += numlen;
/* Get move */
safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
/* Print move */
blank = linelen > 0 && movelen > 0;
if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
fprintf(f, "\n");
linelen = 0;
blank = 0;
}
if (blank) {
fprintf(f, " ");
linelen++;
}
fprintf(f, "%s", move_buffer);
linelen += movelen;
/* [AS] Add PV info if present */
if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
/* [HGM] add time */
char buf[MSG_SIZ]; int seconds;
seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
if( seconds <= 0)
buf[0] = 0;
else
if( seconds < 30 )
snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
else
{
seconds = (seconds + 4)/10; // round to full seconds
if( seconds < 60 )
snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
else
snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
}
if(appData.cumulativeTimePGN) {
snprintf(buf, MSG_SIZ, " %+ld", timeRemaining[i & 1][i+1]/1000);
}
snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
pvInfoList[i].score >= 0 ? "+" : "",
pvInfoList[i].score / 100.0,
pvInfoList[i].depth,
buf );
movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
/* Print score/depth */
blank = linelen > 0 && movelen > 0;
if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
fprintf(f, "\n");
linelen = 0;
blank = 0;
}
if (blank) {
fprintf(f, " ");
linelen++;
}
fprintf(f, "%s", move_buffer);
linelen += movelen;
}
i++;
}
/* Start a new line */
if (linelen > 0) fprintf(f, "\n");
/* Print comments after last move */
if (commentList[i] != NULL) {
fprintf(f, "%s\n", commentList[i]);
}
/* Print result */
if (gameInfo.resultDetails != NULL &&
gameInfo.resultDetails[0] != NULLCHAR) {
char buf[MSG_SIZ], *p = gameInfo.resultDetails;
if(gameInfo.result == GameUnfinished && appData.clockMode &&
(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
} else {
fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
}
}
/* Save game in PGN style and close the file */
int
SaveGamePGN (FILE *f)
{
SaveGamePGN2(f);
fclose(f);
lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
return TRUE;
}
/* Save game in old style and close the file */
int
SaveGameOldStyle (FILE *f)
{
int i, offset;
time_t tm;
tm = time((time_t *) NULL);
fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
PrintOpponents(f);
if (backwardMostMove > 0 || startedFromSetupPosition) {
fprintf(f, "\n[--------------\n");
PrintPosition(f, backwardMostMove);
fprintf(f, "--------------]\n");
} else {
fprintf(f, "\n");
}
i = backwardMostMove;
offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
while (i < forwardMostMove) {
if (commentList[i] != NULL) {
fprintf(f, "[%s]\n", commentList[i]);
}
if ((i % 2) == 1) {
fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
i++;
} else {
fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
i++;
if (commentList[i] != NULL) {
fprintf(f, "\n");
continue;
}
if (i >= forwardMostMove) {
fprintf(f, "\n");
break;
}
fprintf(f, "%s\n", parseList[i]);
i++;
}
}
if (commentList[i] != NULL) {
fprintf(f, "[%s]\n", commentList[i]);
}
/* This isn't really the old style, but it's close enough */
if (gameInfo.resultDetails != NULL &&
gameInfo.resultDetails[0] != NULLCHAR) {
fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
gameInfo.resultDetails);
} else {
fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
}
fclose(f);
return TRUE;
}
/* Save the current game to open file f and close the file */
int
SaveGame (FILE *f, int dummy, char *dummy2)
{
if (gameMode == EditPosition) EditPositionDone(TRUE);
lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
if (appData.oldSaveStyle)
return SaveGameOldStyle(f);
else
return SaveGamePGN(f);
}
/* Save the current position to the given file */
int
SavePositionToFile (char *filename)
{
FILE *f;
char buf[MSG_SIZ];
if (strcmp(filename, "-") == 0) {
return SavePosition(stdout, 0, NULL);
} else {
f = fopen(filename, "a");
if (f == NULL) {
snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
DisplayError(buf, errno);
return FALSE;
} else {
safeStrCpy(buf, lastMsg, MSG_SIZ);
DisplayMessage(_("Waiting for access to save file"), "");
flock(fileno(f), LOCK_EX); // [HGM] lock
DisplayMessage(_("Saving position"), "");
lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
SavePosition(f, 0, NULL);
DisplayMessage(buf, "");
return TRUE;
}
}
}
/* Save the current position to the given open file and close the file */
int
SavePosition (FILE *f, int dummy, char *dummy2)
{
time_t tm;
char *fen;
if (gameMode == EditPosition) EditPositionDone(TRUE);
if (appData.oldSaveStyle) {
tm = time((time_t *) NULL);
fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
PrintOpponents(f);
fprintf(f, "[--------------\n");
PrintPosition(f, currentMove);
fprintf(f, "--------------]\n");
} else {
fen = PositionToFEN(currentMove, NULL, 1);
fprintf(f, "%s\n", fen);
free(fen);
}
fclose(f);
return TRUE;
}
void
ReloadCmailMsgEvent (int unregister)
{
#if !WIN32
static char *inFilename = NULL;
static char *outFilename;
int i;
struct stat inbuf, outbuf;
int status;
/* Any registered moves are unregistered if unregister is set, */
/* i.e. invoked by the signal handler */
if (unregister) {
for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
cmailMoveRegistered[i] = FALSE;
if (cmailCommentList[i] != NULL) {
free(cmailCommentList[i]);
cmailCommentList[i] = NULL;
}
}
nCmailMovesRegistered = 0;
}
for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
cmailResult[i] = CMAIL_NOT_RESULT;
}
nCmailResults = 0;
if (inFilename == NULL) {
/* Because the filenames are static they only get malloced once */
/* and they never get freed */
inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
sprintf(inFilename, "%s.game.in", appData.cmailGameName);
outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
sprintf(outFilename, "%s.out", appData.cmailGameName);
}
status = stat(outFilename, &outbuf);
if (status < 0) {
cmailMailedMove = FALSE;
} else {
status = stat(inFilename, &inbuf);
cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
}
/* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
counts the games, notes how each one terminated, etc.
It would be nice to remove this kludge and instead gather all
the information while building the game list. (And to keep it
in the game list nodes instead of having a bunch of fixed-size
parallel arrays.) Note this will require getting each game's
termination from the PGN tags, as the game list builder does
not process the game moves. --mann
*/
cmailMsgLoaded = TRUE;
LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
/* Load first game in the file or popup game menu */
LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
#endif /* !WIN32 */
return;
}
int
RegisterMove ()
{
FILE *f;
char string[MSG_SIZ];
if ( cmailMailedMove
|| (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
return TRUE; /* Allow free viewing */
}
/* Unregister move to ensure that we don't leave RegisterMove */
/* with the move registered when the conditions for registering no */
/* longer hold */
if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
nCmailMovesRegistered --;
if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
{
free(cmailCommentList[lastLoadGameNumber - 1]);
cmailCommentList[lastLoadGameNumber - 1] = NULL;
}
}
if (cmailOldMove == -1) {
DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
return FALSE;
}
if (currentMove > cmailOldMove + 1) {
DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
return FALSE;
}
if (currentMove < cmailOldMove) {
DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
return FALSE;
}
if (forwardMostMove > currentMove) {
/* Silently truncate extra moves */
TruncateGame();
}
if ( (currentMove == cmailOldMove + 1)
|| ( (currentMove == cmailOldMove)
&& ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
|| (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
if (gameInfo.result != GameUnfinished) {
cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
}
if (commentList[currentMove] != NULL) {
cmailCommentList[lastLoadGameNumber - 1]
= StrSave(commentList[currentMove]);
}
safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
if (appData.debugMode)
fprintf(debugFP, "Saving %s for game %d\n",
cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
f = fopen(string, "w");
if (appData.oldSaveStyle) {
SaveGameOldStyle(f); /* also closes the file */
snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
f = fopen(string, "w");
SavePosition(f, 0, NULL); /* also closes the file */
} else {
fprintf(f, "{--------------\n");
PrintPosition(f, currentMove);
fprintf(f, "--------------}\n\n");
SaveGame(f, 0, NULL); /* also closes the file*/
}
cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
nCmailMovesRegistered ++;
} else if (nCmailGames == 1) {
DisplayError(_("You have not made a move yet"), 0);
return FALSE;
}
return TRUE;
}
void
MailMoveEvent ()
{
#if !WIN32
static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
FILE *commandOutput;
char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
int nBytes = 0; /* Suppress warnings on uninitialized variables */
int nBuffers;
int i;
int archived;
char *arcDir;
if (! cmailMsgLoaded) {
DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
return;
}
if (nCmailGames == nCmailResults) {
DisplayError(_("No unfinished games"), 0);
return;
}
#if CMAIL_PROHIBIT_REMAIL
if (cmailMailedMove) {
snprintf(msg, MSG_SIZ, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
DisplayError(msg, 0);
return;
}
#endif
if (! (cmailMailedMove || RegisterMove())) return;
if ( cmailMailedMove
|| (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
snprintf(string, MSG_SIZ, partCommandString,
appData.debugMode ? " -v" : "", appData.cmailGameName);
commandOutput = popen(string, "r");
if (commandOutput == NULL) {
DisplayError(_("Failed to invoke cmail"), 0);
} else {
for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
}
if (nBuffers > 1) {
(void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
(void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
nBytes = MSG_SIZ - 1;
} else {
(void) memcpy(msg, buffer, nBytes);
}
*(msg + nBytes) = '\0'; /* \0 for end-of-string*/
if(StrStr(msg, "Mailed cmail message to ") != NULL) {
cmailMailedMove = TRUE; /* Prevent >1 moves */
archived = TRUE;
for (i = 0; i < nCmailGames; i ++) {
if (cmailResult[i] == CMAIL_NOT_RESULT) {
archived = FALSE;
}
}
if ( archived
&& ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
!= NULL)) {
snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
arcDir,
appData.cmailGameName,
gameInfo.date);
LoadGameFromFile(buffer, 1, buffer, FALSE);
cmailMsgLoaded = FALSE;
}
}
DisplayInformation(msg);
pclose(commandOutput);
}
} else {
if ((*cmailMsg) != '\0') {
DisplayInformation(cmailMsg);
}
}
return;
#endif /* !WIN32 */
}
char *
CmailMsg ()
{
#if WIN32
return NULL;
#else
int prependComma = 0;
char number[5];
char string[MSG_SIZ]; /* Space for game-list */
int i;
if (!cmailMsgLoaded) return "";
if (cmailMailedMove) {
snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
} else {
/* Create a list of games left */
snprintf(string, MSG_SIZ, "[");
for (i = 0; i < nCmailGames; i ++) {
if (! ( cmailMoveRegistered[i]
|| (cmailResult[i] == CMAIL_OLD_RESULT))) {
if (prependComma) {
snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
} else {
snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
prependComma = 1;
}
strcat(string, number);
}
}
strcat(string, "]");
if (nCmailMovesRegistered + nCmailResults == 0) {
switch (nCmailGames) {
case 1:
snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
break;
case 2:
snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
break;
default:
snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
nCmailGames);
break;
}
} else {
switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
case 1:
snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
string);
break;
case 0:
if (nCmailResults == nCmailGames) {
snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
} else {
snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
}
break;
default:
snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
string);
}
}
}
return cmailMsg;
#endif /* WIN32 */
}
void
ResetGameEvent ()
{
if (gameMode == Training)
SetTrainingModeOff();
Reset(TRUE, TRUE);
cmailMsgLoaded = FALSE;
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("refresh\n");
}
}
void
ExitEvent (int status)
{
exiting++;
if (exiting > 2) {
/* Give up on clean exit */
exit(status);
}
if (exiting > 1) {
/* Keep trying for clean exit */
return;
}
if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
if (telnetISR != NULL) {
RemoveInputSource(telnetISR);
}
if (icsPR != NoProc) {
DestroyChildProcess(icsPR, TRUE);
}
/* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
/* [HGM] crash: the above GameEnds() is a dud if another one was running */
/* make sure this other one finishes before killing it! */
if(endingGame) { int count = 0;
if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
while(endingGame && count++ < 10) DoSleep(1);
if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
}
/* Kill off chess programs */
if (first.pr != NoProc) {
ExitAnalyzeMode();
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", &first);
DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
}
if (second.pr != NoProc) {
DoSleep( appData.delayBeforeQuit );
SendToProgram("quit\n", &second);
DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
}
if (first.isr != NULL) {
RemoveInputSource(first.isr);
}
if (second.isr != NULL) {
RemoveInputSource(second.isr);
}
if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
ShutDownFrontEnd();
exit(status);
}
void
PauseEngine (ChessProgramState *cps)
{
SendToProgram("pause\n", cps);
cps->pause = 2;
}
void
UnPauseEngine (ChessProgramState *cps)
{
SendToProgram("resume\n", cps);
cps->pause = 1;
}
void
PauseEvent ()
{
if (appData.debugMode)
fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
if (pausing) {
pausing = FALSE;
ModeHighlight();
if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
StartClocks();
if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
}
if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
HandleMachineMove(stashedInputMove, stalledEngine);
stalledEngine = NULL;
return;
}
if (gameMode == MachinePlaysWhite ||
gameMode == TwoMachinesPlay ||
gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
if(first.pause) UnPauseEngine(&first);
else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
if(second.pause) UnPauseEngine(&second);
else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
StartClocks();
} else {
DisplayBothClocks();
}
if (gameMode == PlayFromGameFile) {
if (appData.timeDelay >= 0)
AutoPlayGameLoop();
} else if (gameMode == IcsExamining && pauseExamInvalid) {
Reset(FALSE, TRUE);
SendToICS(ics_prefix);
SendToICS("refresh\n");
} else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
ForwardInner(forwardMostMove);
}
pauseExamInvalid = FALSE;
} else {
switch (gameMode) {
default:
return;
case IcsExamining:
pauseExamForwardMostMove = forwardMostMove;
pauseExamInvalid = FALSE;
/* fall through */
case IcsObserving:
case IcsPlayingWhite:
case IcsPlayingBlack:
pausing = TRUE;
ModeHighlight();
return;
case PlayFromGameFile:
(void) StopLoadGameTimer();
pausing = TRUE;
ModeHighlight();
break;
case BeginningOfGame:
if (appData.icsActive) return;
/* else fall through */
case MachinePlaysWhite:
case MachinePlaysBlack:
case TwoMachinesPlay:
if (forwardMostMove == 0)
return; /* don't pause if no one has moved */
if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
if(onMove->pause) { // thinking engine can be paused
PauseEngine(onMove); // do it
if(onMove->other->pause) // pondering opponent can always be paused immediately
PauseEngine(onMove->other);
else
SendToProgram("easy\n", onMove->other);
StopClocks();
} else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
} else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
if(first.pause) {
PauseEngine(&first);
StopClocks();
} else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
} else { // human on move, pause pondering by either method
if(first.pause)
PauseEngine(&first);
else if(appData.ponderNextMove)
SendToProgram("easy\n", &first);
StopClocks();
}
// if no immediate pausing is possible, wait for engine to move, and stop clocks then
case AnalyzeMode:
pausing = TRUE;
ModeHighlight();
break;
}
}
}
void
EditCommentEvent ()
{
char title[MSG_SIZ];
if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
} else {
snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
WhiteOnMove(currentMove - 1) ? " " : ".. ",
parseList[currentMove - 1]);
}
EditCommentPopUp(currentMove, title, commentList[currentMove]);
}
void
EditTagsEvent ()
{
char *tags = PGNTags(&gameInfo);
bookUp = FALSE;
EditTagsPopUp(tags, NULL);
free(tags);
}
void
ToggleSecond ()
{
if(second.analyzing) {
SendToProgram("exit\n", &second);
second.analyzing = FALSE;
} else {
if (second.pr == NoProc) StartChessProgram(&second);
InitChessProgram(&second, FALSE);
FeedMovesToProgram(&second, currentMove);
SendToProgram("analyze\n", &second);
second.analyzing = TRUE;
}
}
/* Toggle ShowThinking */
void
ToggleShowThinking()
{
appData.showThinking = !appData.showThinking;
ShowThinkingEvent();
}
int
AnalyzeModeEvent ()
{
char buf[MSG_SIZ];
if (!first.analysisSupport) {
snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
DisplayError(buf, 0);
return 0;
}
/* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
if (appData.icsActive) {
if (gameMode != IcsObserving) {
snprintf(buf, MSG_SIZ, _("You are not observing a game"));
DisplayError(buf, 0);
/* secure check */
if (appData.icsEngineAnalyze) {
if (appData.debugMode)
fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
ExitAnalyzeMode();
ModeHighlight();
}
return 0;
}
/* if enable, user wants to disable icsEngineAnalyze */
if (appData.icsEngineAnalyze) {
ExitAnalyzeMode();
ModeHighlight();
return 0;
}
appData.icsEngineAnalyze = TRUE;
if (appData.debugMode)
fprintf(debugFP, "ICS engine analyze starting... \n");
}
if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
if (appData.noChessProgram || gameMode == AnalyzeMode)
return 0;
if (gameMode != AnalyzeFile) {
if (!appData.icsEngineAnalyze) {
EditGameEvent();
if (gameMode != EditGame) return 0;
}
if (!appData.showThinking) ToggleShowThinking();
ResurrectChessProgram();
SendToProgram("analyze\n", &first);
first.analyzing = TRUE;
/*first.maybeThinking = TRUE;*/
first.maybeThinking = FALSE; /* avoid killing GNU Chess */
EngineOutputPopUp();
}
if (!appData.icsEngineAnalyze) {
gameMode = AnalyzeMode;
ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
}
pausing = FALSE;
ModeHighlight();
SetGameInfo();
StartAnalysisClock();
GetTimeMark(&lastNodeCountTime);
lastNodeCount = 0;
return 1;
}
void
AnalyzeFileEvent ()
{
if (appData.noChessProgram || gameMode == AnalyzeFile)
return;
if (!first.analysisSupport) {
char buf[MSG_SIZ];
snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
DisplayError(buf, 0);
return;
}
if (gameMode != AnalyzeMode) {
keepInfo = 1; // mere annotating should not alter PGN tags
EditGameEvent();
keepInfo = 0;
if (gameMode != EditGame) return;
if (!appData.showThinking) ToggleShowThinking();
ResurrectChessProgram();
SendToProgram("analyze\n", &first);
first.analyzing = TRUE;
/*first.maybeThinking = TRUE;*/
first.maybeThinking = FALSE; /* avoid killing GNU Chess */
EngineOutputPopUp();
}
gameMode = AnalyzeFile;
pausing = FALSE;
ModeHighlight();
StartAnalysisClock();
GetTimeMark(&lastNodeCountTime);
lastNodeCount = 0;
if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
AnalysisPeriodicEvent(1);
}
void
MachineWhiteEvent ()
{
char buf[MSG_SIZ];
char *bookHit = NULL;
if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
return;
if (gameMode == PlayFromGameFile ||
gameMode == TwoMachinesPlay ||
gameMode == Training ||
gameMode == AnalyzeMode ||
gameMode == EndOfGame)
EditGameEvent();
if (gameMode == EditPosition)
EditPositionDone(TRUE);
if (!WhiteOnMove(currentMove)) {
DisplayError(_("It is not White's turn"), 0);
return;
}
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
ExitAnalyzeMode();
if (gameMode == EditGame || gameMode == AnalyzeMode ||
gameMode == AnalyzeFile)
TruncateGame();
ResurrectChessProgram(); /* in case it isn't running */
if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
gameMode = MachinePlaysWhite;
ResetClocks();
} else
gameMode = MachinePlaysWhite;
pausing = FALSE;
ModeHighlight();
SetGameInfo();
snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
DisplayTitle(buf);
if (first.sendName) {
snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
SendToProgram(buf, &first);
}
if (first.sendTime) {
if (first.useColors) {
SendToProgram("black\n", &first); /*gnu kludge*/
}
SendTimeRemaining(&first, TRUE);
}
if (first.useColors) {
SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
}
bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
SetMachineThinkingEnables();
first.maybeThinking = TRUE;
StartClocks();
firstMove = FALSE;
if (appData.autoFlipView && !flipView) {
flipView = !flipView;
DrawPosition(FALSE, NULL);
DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
}
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
savedMessage = bookMove; // args for deferred call
savedState = &first;
ScheduleDelayedEvent(DeferredBookMove, 1);
}
}
void
MachineBlackEvent ()
{
char buf[MSG_SIZ];
char *bookHit = NULL;
if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
return;
if (gameMode == PlayFromGameFile ||
gameMode == TwoMachinesPlay ||
gameMode == Training ||
gameMode == AnalyzeMode ||
gameMode == EndOfGame)
EditGameEvent();
if (gameMode == EditPosition)
EditPositionDone(TRUE);
if (WhiteOnMove(currentMove)) {
DisplayError(_("It is not Black's turn"), 0);
return;
}
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
ExitAnalyzeMode();
if (gameMode == EditGame || gameMode == AnalyzeMode ||
gameMode == AnalyzeFile)
TruncateGame();
ResurrectChessProgram(); /* in case it isn't running */
gameMode = MachinePlaysBlack;
pausing = FALSE;
ModeHighlight();
SetGameInfo();
snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
DisplayTitle(buf);
if (first.sendName) {
snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
SendToProgram(buf, &first);
}
if (first.sendTime) {
if (first.useColors) {
SendToProgram("white\n", &first); /*gnu kludge*/
}
SendTimeRemaining(&first, FALSE);
}
if (first.useColors) {
SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
}
bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
SetMachineThinkingEnables();
first.maybeThinking = TRUE;
StartClocks();
if (appData.autoFlipView && flipView) {
flipView = !flipView;
DrawPosition(FALSE, NULL);
DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
}
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
savedMessage = bookMove; // args for deferred call
savedState = &first;
ScheduleDelayedEvent(DeferredBookMove, 1);
}
}
void
DisplayTwoMachinesTitle ()
{
char buf[MSG_SIZ];
if (appData.matchGames > 0) {
if(appData.tourneyFile[0]) {
snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
gameInfo.white, _("vs."), gameInfo.black,
nextGame+1, appData.matchGames+1,
appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
} else
if (first.twoMachinesColor[0] == 'w') {
snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
gameInfo.white, _("vs."), gameInfo.black,
first.matchWins, second.matchWins,
matchGame - 1 - (first.matchWins + second.matchWins));
} else {
snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
gameInfo.white, _("vs."), gameInfo.black,
second.matchWins, first.matchWins,
matchGame - 1 - (first.matchWins + second.matchWins));
}
} else {
snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
}
DisplayTitle(buf);
}
void
SettingsMenuIfReady ()
{
if (second.lastPing != second.lastPong) {
DisplayMessage("", _("Waiting for second chess program"));
ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
return;
}
ThawUI();
DisplayMessage("", "");
SettingsPopUp(&second);
}
int
WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
{
char buf[MSG_SIZ];
if (cps->pr == NoProc) {
StartChessProgram(cps);
if (cps->protocolVersion == 1) {
retry();
ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
} else {
/* kludge: allow timeout for initial "feature" command */
if(retry != TwoMachinesEventIfReady) FreezeUI();
snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
DisplayMessage("", buf);
ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
}
return 1;
}
return 0;
}
void
TwoMachinesEvent P((void))
{
int i;
char buf[MSG_SIZ];
ChessProgramState *onmove;
char *bookHit = NULL;
static int stalling = 0;
TimeMark now;
long wait;
if (appData.noChessProgram) return;
switch (gameMode) {
case TwoMachinesPlay:
return;
case MachinePlaysWhite:
case MachinePlaysBlack:
if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
return;
}
/* fall through */
case BeginningOfGame:
case PlayFromGameFile:
case EndOfGame:
EditGameEvent();
if (gameMode != EditGame) return;
break;
case EditPosition:
EditPositionDone(TRUE);
break;
case AnalyzeMode:
case AnalyzeFile:
ExitAnalyzeMode();
break;
case EditGame:
default:
break;
}
// forwardMostMove = currentMove;
TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
startingEngine = TRUE;
if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
return;
}
if(!appData.epd) {
if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
startingEngine = matchMode = FALSE;
DisplayError("second engine does not play this", 0);
gameMode = TwoMachinesPlay; ModeHighlight(); // Needed to make sure menu item is unchecked
EditGameEvent(); // switch back to EditGame mode
return;
}
if(!stalling) {
InitChessProgram(&second, FALSE); // unbalances ping of second engine
SendToProgram("force\n", &second);
stalling = 1;
ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
return;
}
}
GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
if(appData.matchPause>10000 || appData.matchPause<10)
appData.matchPause = 10000; /* [HGM] make pause adjustable */
wait = SubtractTimeMarks(&now, &pauseStart);
if(wait < appData.matchPause) {
ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
return;
}
// we are now committed to starting the game
stalling = 0;
DisplayMessage("", "");
if(!appData.epd) {
if (startedFromSetupPosition) {
SendBoard(&second, backwardMostMove);
if (appData.debugMode) {
fprintf(debugFP, "Two Machines\n");
}
}
for (i = backwardMostMove; i < forwardMostMove; i++) {
SendMoveToProgram(i, &second);
}
}
gameMode = TwoMachinesPlay;
pausing = startingEngine = FALSE;
ModeHighlight(); // [HGM] logo: this triggers display update of logos
SetGameInfo();
DisplayTwoMachinesTitle();
firstMove = TRUE;
if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
onmove = &first;
} else {
onmove = &second;
}
if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
SendToProgram(first.computerString, &first);
if (first.sendName) {
snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
SendToProgram(buf, &first);
}
if(!appData.epd) {
SendToProgram(second.computerString, &second);
if (second.sendName) {
snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
SendToProgram(buf, &second);
}
}
ResetClocks();
if (!first.sendTime || !second.sendTime) {
timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
timeRemaining[1][forwardMostMove] = blackTimeRemaining;
}
if (onmove->sendTime) {
if (onmove->useColors) {
SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
}
SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
}
if (onmove->useColors) {
SendToProgram(onmove->twoMachinesColor, onmove);
}
bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
// SendToProgram("go\n", onmove);
onmove->maybeThinking = TRUE;
SetMachineThinkingEnables();
StartClocks();
if(bookHit) { // [HGM] book: simulate book reply
static char bookMove[MSG_SIZ]; // a bit generous?
programStats.nodes = programStats.depth = programStats.time =
programStats.score = programStats.got_only_move = 0;
sprintf(programStats.movelist, "%s (xbook)", bookHit);
safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
strcat(bookMove, bookHit);
savedMessage = bookMove; // args for deferred call
savedState = onmove;
ScheduleDelayedEvent(DeferredBookMove, 1);
}
}
void
TrainingEvent ()
{
if (gameMode == Training) {
SetTrainingModeOff();
gameMode = PlayFromGameFile;
DisplayMessage("", _("Training mode off"));
} else {
gameMode = Training;
animateTraining = appData.animate;
/* make sure we are not already at the end of the game */
if (currentMove < forwardMostMove) {
SetTrainingModeOn();
DisplayMessage("", _("Training mode on"));
} else {
gameMode = PlayFromGameFile;
DisplayError(_("Already at end of game"), 0);
}
}
ModeHighlight();
}
void
IcsClientEvent ()
{
if (!appData.icsActive) return;
switch (gameMode) {
case IcsPlayingWhite:
case IcsPlayingBlack:
case IcsObserving:
case IcsIdle:
case BeginningOfGame:
case IcsExamining:
return;
case EditGame:
break;
case EditPosition:
EditPositionDone(TRUE);
break;
case AnalyzeMode:
case AnalyzeFile:
ExitAnalyzeMode();
break;
default:
EditGameEvent();
break;
}
gameMode = IcsIdle;
ModeHighlight();
return;
}
void
EditGameEvent ()
{
int i;
switch (gameMode) {
case Training:
SetTrainingModeOff();
break;
case MachinePlaysWhite:
case MachinePlaysBlack:
case BeginningOfGame:
SendToProgram("force\n", &first);
if(gameMode == (forwardMostMove & 1 ? MachinePlaysBlack : MachinePlaysWhite)) { // engine is thinking
if (first.usePing) { // [HGM] always send ping when we might interrupt machine thinking
char buf[MSG_SIZ];
abortEngineThink = TRUE;
snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++first.lastPing);
SendToProgram(buf, &first);
DisplayMessage("Aborting engine think", "");
FreezeUI();
}
}
SetUserThinkingEnables();
break;
case PlayFromGameFile:
(void) StopLoadGameTimer();
if (gameFileFP != NULL) {
gameFileFP = NULL;
}
break;
case EditPosition:
EditPositionDone(TRUE);
break;
case AnalyzeMode:
case AnalyzeFile:
ExitAnalyzeMode();
SendToProgram("force\n", &first);
break;
case TwoMachinesPlay:
GameEnds(EndOfFile, NULL, GE_PLAYER);
ResurrectChessProgram();
SetUserThinkingEnables();
break;
case EndOfGame:
ResurrectChessProgram();
break;
case IcsPlayingBlack:
case IcsPlayingWhite:
DisplayError(_("Warning: You are still playing a game"), 0);
break;
case IcsObserving:
DisplayError(_("Warning: You are still observing a game"), 0);
break;
case IcsExamining:
DisplayError(_("Warning: You are still examining a game"), 0);
break;
case IcsIdle:
break;
case EditGame:
default:
return;
}
pausing = FALSE;
StopClocks();
first.offeredDraw = second.offeredDraw = 0;
if (gameMode == PlayFromGameFile) {
whiteTimeRemaining = timeRemaining[0][currentMove];
blackTimeRemaining = timeRemaining[1][currentMove];
DisplayTitle("");
}
if (gameMode == MachinePlaysWhite ||
gameMode == MachinePlaysBlack ||
gameMode == TwoMachinesPlay ||
gameMode == EndOfGame) {
i = forwardMostMove;
while (i > currentMove) {
SendToProgram("undo\n", &first);
i--;
}
if(!adjustedClock) {
whiteTimeRemaining = timeRemaining[0][currentMove];
blackTimeRemaining = timeRemaining[1][currentMove];
DisplayBothClocks();
}
if (whiteFlag || blackFlag) {
whiteFlag = blackFlag = 0;
}
DisplayTitle("");
}
gameMode = EditGame;
ModeHighlight();
SetGameInfo();
}
void
EditPositionEvent ()
{
int i;
if (gameMode == EditPosition) {
EditGameEvent();
return;
}
EditGameEvent();
if (gameMode != EditGame) return;
gameMode = EditPosition;
ModeHighlight();
SetGameInfo();
CopyBoard(rightsBoard, nullBoard);
if (currentMove > 0)
CopyBoard(boards[0], boards[currentMove]);
for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
blackPlaysFirst = !WhiteOnMove(currentMove);
ResetClocks();
currentMove = forwardMostMove = backwardMostMove = 0;
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
DisplayMove(-1);
if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
}
void
ExitAnalyzeMode ()
{
/* [DM] icsEngineAnalyze - possible call from other functions */
if (appData.icsEngineAnalyze) {
appData.icsEngineAnalyze = FALSE;
DisplayMessage("",_("Close ICS engine analyze..."));
}
if (first.analysisSupport && first.analyzing) {
SendToBoth("exit\n");
first.analyzing = second.analyzing = FALSE;
}
thinkOutput[0] = NULLCHAR;
}
void
EditPositionDone (Boolean fakeRights)
{
int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
startedFromSetupPosition = TRUE;
InitChessProgram(&first, FALSE);
if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
int r, f;
boards[0][EP_STATUS] = EP_NONE;
for(f=0; f<=nrCastlingRights; f++) boards[0][CASTLING][f] = NoRights;
for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // first pass: Kings & e.p.
if(rightsBoard[r][f]) {
ChessSquare p = boards[0][r][f];
if(p == (blackPlaysFirst ? WhitePawn : BlackPawn)) boards[0][EP_STATUS] = f;
else if(p == king) boards[0][CASTLING][2] = f;
else if(p == WHITE_TO_BLACK king) boards[0][CASTLING][5] = f;
else rightsBoard[r][f] = 2; // mark for second pass
}
}
for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // second pass: Rooks
if(rightsBoard[r][f] == 2) {
ChessSquare p = boards[0][r][f];
if(p == WhiteRook) boards[0][CASTLING][(f < boards[0][CASTLING][2])] = f; else
if(p == BlackRook) boards[0][CASTLING][(f < boards[0][CASTLING][5])+3] = f;
}
}
}
SendToProgram("force\n", &first);
if (blackPlaysFirst) {
safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
currentMove = forwardMostMove = backwardMostMove = 1;
CopyBoard(boards[1], boards[0]);
} else {
currentMove = forwardMostMove = backwardMostMove = 0;
}
SendBoard(&first, forwardMostMove);
if (appData.debugMode) {
fprintf(debugFP, "EditPosDone\n");
}
DisplayTitle("");
DisplayMessage("", "");
timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
timeRemaining[1][forwardMostMove] = blackTimeRemaining;
gameMode = EditGame;
ModeHighlight();
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
ClearHighlights(); /* [AS] */
}
/* Pause for `ms' milliseconds */
/* !! Ugh, this is a kludge. Fix it sometime. --tpm */
void
TimeDelay (long ms)
{
TimeMark m1, m2;
GetTimeMark(&m1);
do {
GetTimeMark(&m2);
} while (SubtractTimeMarks(&m2, &m1) < ms);
}
/* !! Ugh, this is a kludge. Fix it sometime. --tpm */
void
SendMultiLineToICS (char *buf)
{
char temp[MSG_SIZ+1], *p;
int len;
len = strlen(buf);
if (len > MSG_SIZ)
len = MSG_SIZ;
strncpy(temp, buf, len);
temp[len] = 0;
p = temp;
while (*p) {
if (*p == '\n' || *p == '\r')
*p = ' ';
++p;
}
strcat(temp, "\n");
SendToICS(temp);
SendToPlayer(temp, strlen(temp));
}
void
SetWhiteToPlayEvent ()
{
if (gameMode == EditPosition) {
blackPlaysFirst = FALSE;
DisplayBothClocks(); /* works because currentMove is 0 */
} else if (gameMode == IcsExamining) {
SendToICS(ics_prefix);
SendToICS("tomove white\n");
}
}
void
SetBlackToPlayEvent ()
{
if (gameMode == EditPosition) {
blackPlaysFirst = TRUE;
currentMove = 1; /* kludge */
DisplayBothClocks();
currentMove = 0;
} else if (gameMode == IcsExamining) {
SendToICS(ics_prefix);
SendToICS("tomove black\n");
}
}
void
EditPositionMenuEvent (ChessSquare selection, int x, int y)
{
char buf[MSG_SIZ];
ChessSquare piece = boards[0][y][x];
static Board erasedBoard, currentBoard, menuBoard, nullBoard;
static int lastVariant;
int baseRank = BOARD_HEIGHT-1, hasRights = 0;
if (gameMode != EditPosition && gameMode != IcsExamining) return;
switch (selection) {
case ClearBoard:
fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
MarkTargetSquares(1);
CopyBoard(currentBoard, boards[0]);
CopyBoard(menuBoard, initialPosition);
if (gameMode == IcsExamining && ics_type == ICS_FICS) {
SendToICS(ics_prefix);
SendToICS("bsetup clear\n");
} else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
SendToICS(ics_prefix);
SendToICS("clearboard\n");
} else {
int nonEmpty = 0;
for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
for (y = 0; y < BOARD_HEIGHT; y++) {
if (gameMode == IcsExamining) {
if (boards[currentMove][y][x] != EmptySquare) {
snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
AAA + x, ONE + y);
SendToICS(buf);
}
} else if(boards[0][y][x] != DarkSquare) {
if(boards[0][y][x] != p) nonEmpty++;
boards[0][y][x] = p;
}
}
}
CopyBoard(rightsBoard, nullBoard);
if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
int r, i;
for(r = 0; r < BOARD_HEIGHT; r++) {
for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates
ChessSquare p = menuBoard[r][x];
for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
}
}
menuBoard[CASTLING][0] = menuBoard[CASTLING][3] = NoRights; // h-side Rook was deleted
DisplayMessage("Clicking clock again restores position", "");
if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
if(!nonEmpty) { // asked to clear an empty board
CopyBoard(boards[0], menuBoard);
} else
if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
CopyBoard(boards[0], initialPosition);
} else
if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
&& !CompareBoards(nullBoard, erasedBoard)) {
CopyBoard(boards[0], erasedBoard);
} else
CopyBoard(erasedBoard, currentBoard);
for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
}
}
if (gameMode == EditPosition) {
DrawPosition(FALSE, boards[0]);
}
break;
case WhitePlay:
SetWhiteToPlayEvent();
break;
case BlackPlay:
SetBlackToPlayEvent();
break;
case EmptySquare:
if (gameMode == IcsExamining) {
if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
SendToICS(buf);
} else {
if(x < BOARD_LEFT || x >= BOARD_RGHT) {
if(x == BOARD_LEFT-2) {
if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
boards[0][y][1] = 0;
} else
if(x == BOARD_RGHT+1) {
if(y >= gameInfo.holdingsSize) break;
boards[0][y][BOARD_WIDTH-2] = 0;
} else break;
}
boards[0][y][x] = EmptySquare;
DrawPosition(FALSE, boards[0]);
}
break;
case PromotePiece:
if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
piece >= (int)BlackPawn && piece < (int)BlackMan ) {
selection = (ChessSquare) (PROMOTED(piece));
} else if(piece == EmptySquare) selection = WhiteSilver;
else selection = (ChessSquare)((int)piece - 1);
goto defaultlabel;
case DemotePiece:
if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
piece > (int)BlackMan && piece <= (int)BlackKing ) {
selection = (ChessSquare) (DEMOTED(piece));
} else if(piece == EmptySquare) selection = BlackSilver;
else selection = (ChessSquare)((int)piece + 1);
goto defaultlabel;
case WhiteQueen:
case BlackQueen:
if(gameInfo.variant == VariantShatranj ||
gameInfo.variant == VariantXiangqi ||
gameInfo.variant == VariantCourier ||
gameInfo.variant == VariantASEAN ||
gameInfo.variant == VariantMakruk )
selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
goto defaultlabel;
case WhiteRook:
baseRank = 0;
case BlackRook:
if(y == baseRank && (x == BOARD_LEFT || x == BOARD_RGHT-1 || appData.fischerCastling)) hasRights = 1;
if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
goto defaultlabel;
case WhiteKing:
baseRank = 0;
case BlackKing:
if(gameInfo.variant == VariantXiangqi)
selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
if(gameInfo.variant == VariantKnightmate)
selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
default:
defaultlabel:
if (gameMode == IcsExamining) {
if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
PieceToChar(selection), AAA + x, ONE + y);
SendToICS(buf);
} else {
rightsBoard[y][x] = hasRights;
if(x < BOARD_LEFT || x >= BOARD_RGHT) {
int n;
if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
n = PieceToNumber(selection - BlackPawn);
if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
boards[0][BOARD_HEIGHT-1-n][0] = selection;
boards[0][BOARD_HEIGHT-1-n][1]++;
} else
if(x == BOARD_RGHT+1 && selection < BlackPawn) {
n = PieceToNumber(selection);
if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
boards[0][n][BOARD_WIDTH-1] = selection;
boards[0][n][BOARD_WIDTH-2]++;
}
} else
boards[0][y][x] = selection;
DrawPosition(TRUE, boards[0]);
ClearHighlights();
fromX = fromY = -1;
}
break;
}
}
void
DropMenuEvent (ChessSquare selection, int x, int y)
{
ChessMove moveType;
switch (gameMode) {
case IcsPlayingWhite:
case MachinePlaysBlack:
if (!WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is Black's turn"));
return;
}
moveType = WhiteDrop;
break;
case IcsPlayingBlack:
case MachinePlaysWhite:
if (WhiteOnMove(currentMove)) {
DisplayMoveError(_("It is White's turn"));
return;
}
moveType = BlackDrop;
break;
case EditGame:
moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
break;
default:
return;
}
if (moveType == BlackDrop && selection < BlackPawn) {
selection = (ChessSquare) ((int) selection
+ (int) BlackPawn - (int) WhitePawn);
}
if (boards[currentMove][y][x] != EmptySquare) {
DisplayMoveError(_("That square is occupied"));
return;
}
FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
}
void
AcceptEvent ()
{
/* Accept a pending offer of any kind from opponent */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("accept\n");
} else if (cmailMsgLoaded) {
if (currentMove == cmailOldMove &&
commentList[cmailOldMove] != NULL &&
StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
"Black offers a draw" : "White offers a draw")) {
TruncateGame();
GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
} else {
DisplayError(_("There is no pending offer on this move"), 0);
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
}
} else {
/* Not used for offers from chess program */
}
}
void
DeclineEvent ()
{
/* Decline a pending offer of any kind from opponent */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("decline\n");
} else if (cmailMsgLoaded) {
if (currentMove == cmailOldMove &&
commentList[cmailOldMove] != NULL &&
StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
"Black offers a draw" : "White offers a draw")) {
#ifdef NOTDEF
AppendComment(cmailOldMove, "Draw declined", TRUE);
DisplayComment(cmailOldMove - 1, "Draw declined");
#endif /*NOTDEF*/
} else {
DisplayError(_("There is no pending offer on this move"), 0);
}
} else {
/* Not used for offers from chess program */
}
}
void
RematchEvent ()
{
/* Issue ICS rematch command */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("rematch\n");
}
}
void
CallFlagEvent ()
{
/* Call your opponent's flag (claim a win on time) */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("flag\n");
} else {
switch (gameMode) {
default:
return;
case MachinePlaysWhite:
if (whiteFlag) {
if (blackFlag)
GameEnds(GameIsDrawn, "Both players ran out of time",
GE_PLAYER);
else
GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
} else {
DisplayError(_("Your opponent is not out of time"), 0);
}
break;
case MachinePlaysBlack:
if (blackFlag) {
if (whiteFlag)
GameEnds(GameIsDrawn, "Both players ran out of time",
GE_PLAYER);
else
GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
} else {
DisplayError(_("Your opponent is not out of time"), 0);
}
break;
}
}
}
void
ClockClick (int which)
{ // [HGM] code moved to back-end from winboard.c
if(which) { // black clock
if (gameMode == EditPosition || gameMode == IcsExamining) {
if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
SetBlackToPlayEvent();
} else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
} else if (shiftKey) {
AdjustClock(which, -1);
} else if (gameMode == IcsPlayingWhite ||
gameMode == MachinePlaysBlack) {
CallFlagEvent();
}
} else { // white clock
if (gameMode == EditPosition || gameMode == IcsExamining) {
if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
SetWhiteToPlayEvent();
} else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
} else if (shiftKey) {
AdjustClock(which, -1);
} else if (gameMode == IcsPlayingBlack ||
gameMode == MachinePlaysWhite) {
CallFlagEvent();
}
}
}
void
DrawEvent ()
{
/* Offer draw or accept pending draw offer from opponent */
if (appData.icsActive) {
/* Note: tournament rules require draw offers to be
made after you make your move but before you punch
your clock. Currently ICS doesn't let you do that;
instead, you immediately punch your clock after making
a move, but you can offer a draw at any time. */
SendToICS(ics_prefix);
SendToICS("draw\n");
userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
} else if (cmailMsgLoaded) {
if (currentMove == cmailOldMove &&
commentList[cmailOldMove] != NULL &&
StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
"Black offers a draw" : "White offers a draw")) {
GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
} else if (currentMove == cmailOldMove + 1) {
char *offer = WhiteOnMove(cmailOldMove) ?
"White offers a draw" : "Black offers a draw";
AppendComment(currentMove, offer, TRUE);
DisplayComment(currentMove - 1, offer);
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
} else {
DisplayError(_("You must make your move before offering a draw"), 0);
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
}
} else if (first.offeredDraw) {
GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
} else {
if (first.sendDrawOffers) {
SendToProgram("draw\n", &first);
userOfferedDraw = TRUE;
}
}
}
void
AdjournEvent ()
{
/* Offer Adjourn or accept pending Adjourn offer from opponent */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("adjourn\n");
} else {
/* Currently GNU Chess doesn't offer or accept Adjourns */
}
}
void
AbortEvent ()
{
/* Offer Abort or accept pending Abort offer from opponent */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("abort\n");
} else {
GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
}
}
void
ResignEvent ()
{
/* Resign. You can do this even if it's not your turn. */
if (appData.icsActive) {
SendToICS(ics_prefix);
SendToICS("resign\n");
} else {
switch (gameMode) {
case MachinePlaysWhite:
GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
break;
case MachinePlaysBlack:
GameEnds(BlackWins, "White resigns", GE_PLAYER);
break;
case EditGame:
if (cmailMsgLoaded) {
TruncateGame();
if (WhiteOnMove(cmailOldMove)) {
GameEnds(BlackWins, "White resigns", GE_PLAYER);
} else {
GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
}
cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
}
break;
default:
break;
}
}
}
void
StopObservingEvent ()
{
/* Stop observing current games */
SendToICS(ics_prefix);
SendToICS("unobserve\n");
}
void
StopExaminingEvent ()
{
/* Stop observing current game */
SendToICS(ics_prefix);
SendToICS("unexamine\n");
}
void
ForwardInner (int target)
{
int limit; int oldSeekGraphUp = seekGraphUp;
if (appData.debugMode)
fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
target, currentMove, forwardMostMove);
if (gameMode == EditPosition)
return;
seekGraphUp = FALSE;
MarkTargetSquares(1);
fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
if (gameMode == PlayFromGameFile && !pausing)
PauseEvent();
if (gameMode == IcsExamining && pausing)
limit = pauseExamForwardMostMove;
else
limit = forwardMostMove;
if (target > limit) target = limit;
if (target > 0 && moveList[target - 1][0]) {
int fromX, fromY, toX, toY;
toX = moveList[target - 1][2] - AAA;
toY = moveList[target - 1][3] - ONE;
if (moveList[target - 1][1] == '@') {
if (appData.highlightLastMove) {
SetHighlights(-1, -1, toX, toY);
}
} else {
fromX = moveList[target - 1][0] - AAA;
fromY = moveList[target - 1][1] - ONE;
if (target == currentMove + 1) {
if(moveList[target - 1][4] == ';') { // multi-leg
killX = moveList[target - 1][5] - AAA;
killY = moveList[target - 1][6] - ONE;
}
AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
killX = killY = -1;
}
if (appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
}
}
}
if (gameMode == EditGame || gameMode == AnalyzeMode ||
gameMode == Training || gameMode == PlayFromGameFile ||
gameMode == AnalyzeFile) {
while (currentMove < target) {
if(second.analyzing) SendMoveToProgram(currentMove, &second);
SendMoveToProgram(currentMove++, &first);
}
} else {
currentMove = target;
}
if (gameMode == EditGame || gameMode == EndOfGame) {
whiteTimeRemaining = timeRemaining[0][currentMove];
blackTimeRemaining = timeRemaining[1][currentMove];
}
DisplayBothClocks();
DisplayMove(currentMove - 1);
DrawPosition(oldSeekGraphUp, boards[currentMove]);
HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
DisplayComment(currentMove - 1, commentList[currentMove]);
}
ClearMap(); // [HGM] exclude: invalidate map
}
void
ForwardEvent ()
{
if (gameMode == IcsExamining && !pausing) {
SendToICS(ics_prefix);
SendToICS("forward\n");
} else {
ForwardInner(currentMove + 1);
}
}
void
ToEndEvent ()
{
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
/* to optimze, we temporarily turn off analysis mode while we feed
* the remaining moves to the engine. Otherwise we get analysis output
* after each move.
*/
if (first.analysisSupport) {
SendToProgram("exit\nforce\n", &first);
first.analyzing = FALSE;
}
}
if (gameMode == IcsExamining && !pausing) {
SendToICS(ics_prefix);
SendToICS("forward 999999\n");
} else {
ForwardInner(forwardMostMove);
}
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
/* we have fed all the moves, so reactivate analysis mode */
SendToProgram("analyze\n", &first);
first.analyzing = TRUE;
/*first.maybeThinking = TRUE;*/
first.maybeThinking = FALSE; /* avoid killing GNU Chess */
}
}
void
BackwardInner (int target)
{
int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
if (appData.debugMode)
fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
target, currentMove, forwardMostMove);
if (gameMode == EditPosition) return;
seekGraphUp = FALSE;
MarkTargetSquares(1);
fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
if (currentMove <= backwardMostMove) {
ClearHighlights();
DrawPosition(full_redraw, boards[currentMove]);
return;
}
if (gameMode == PlayFromGameFile && !pausing)
PauseEvent();
if (moveList[target][0]) {
int fromX, fromY, toX, toY;
toX = moveList[target][2] - AAA;
toY = moveList[target][3] - ONE;
if (moveList[target][1] == '@') {
if (appData.highlightLastMove) {
SetHighlights(-1, -1, toX, toY);
}
} else {
fromX = moveList[target][0] - AAA;
fromY = moveList[target][1] - ONE;
if (target == currentMove - 1) {
AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
}
if (appData.highlightLastMove) {
SetHighlights(fromX, fromY, toX, toY);
}
}
}
if (gameMode == EditGame || gameMode==AnalyzeMode ||
gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
while (currentMove > target) {
if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
// null move cannot be undone. Reload program with move history before it.
int i;
for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
}
SendBoard(&first, i);
if(second.analyzing) SendBoard(&second, i);
for(currentMove=i; currentMove<target; currentMove++) {
SendMoveToProgram(currentMove, &first);
if(second.analyzing) SendMoveToProgram(currentMove, &second);
}
break;
}
SendToBoth("undo\n");
currentMove--;
}
} else {
currentMove = target;
}
if (gameMode == EditGame || gameMode == EndOfGame) {
whiteTimeRemaining = timeRemaining[0][currentMove];
blackTimeRemaining = timeRemaining[1][currentMove];
}
DisplayBothClocks();
DisplayMove(currentMove - 1);
DrawPosition(full_redraw, boards[currentMove]);
HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
// [HGM] PV info: routine tests if comment empty
DisplayComment(currentMove - 1, commentList[currentMove]);
ClearMap(); // [HGM] exclude: invalidate map
}
void
BackwardEvent ()
{
if (gameMode == IcsExamining && !pausing) {
SendToICS(ics_prefix);
SendToICS("backward\n");
} else {
BackwardInner(currentMove - 1);
}
}
void
ToStartEvent ()
{
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
/* to optimize, we temporarily turn off analysis mode while we undo
* all the moves. Otherwise we get analysis output after each undo.
*/
if (first.analysisSupport) {
SendToProgram("exit\nforce\n", &first);
first.analyzing = FALSE;
}
}
if (gameMode == IcsExamining && !pausing) {
SendToICS(ics_prefix);
SendToICS("backward 999999\n");
} else {
BackwardInner(backwardMostMove);
}
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
/* we have fed all the moves, so reactivate analysis mode */
SendToProgram("analyze\n", &first);
first.analyzing = TRUE;
/*first.maybeThinking = TRUE;*/
first.maybeThinking = FALSE; /* avoid killing GNU Chess */
}
}
void
ToNrEvent (int to)
{
if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
if (to >= forwardMostMove) to = forwardMostMove;
if (to <= backwardMostMove) to = backwardMostMove;
if (to < currentMove) {
BackwardInner(to);
} else {
ForwardInner(to);
}
}
void
RevertEvent (Boolean annotate)
{
if(PopTail(annotate)) { // [HGM] vari: restore old game tail
return;
}
if (gameMode != IcsExamining) {
DisplayError(_("You are not examining a game"), 0);
return;
}
if (pausing) {
DisplayError(_("You can't revert while pausing"), 0);
return;
}
SendToICS(ics_prefix);
SendToICS("revert\n");
}
void
RetractMoveEvent ()
{
switch (gameMode) {
case MachinePlaysWhite:
case MachinePlaysBlack:
if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
return;
}
if (forwardMostMove < 2) return;
currentMove = forwardMostMove = forwardMostMove - 2;
whiteTimeRemaining = timeRemaining[0][currentMove];
blackTimeRemaining = timeRemaining[1][currentMove];
DisplayBothClocks();
DisplayMove(currentMove - 1);
ClearHighlights();/*!! could figure this out*/
DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
SendToProgram("remove\n", &first);
/*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
break;
case BeginningOfGame:
default:
break;
case IcsPlayingWhite:
case IcsPlayingBlack:
if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
SendToICS(ics_prefix);
SendToICS("takeback 2\n");
} else {
SendToICS(ics_prefix);
SendToICS("takeback 1\n");
}
break;
}
}
void
MoveNowEvent ()
{
ChessProgramState *cps;
switch (gameMode) {
case MachinePlaysWhite:
if (!WhiteOnMove(forwardMostMove)) {
DisplayError(_("It is your turn"), 0);
return;
}
cps = &first;
break;
case MachinePlaysBlack:
if (WhiteOnMove(forwardMostMove)) {
DisplayError(_("It is your turn"), 0);
return;
}
cps = &first;
break;
case TwoMachinesPlay:
if (WhiteOnMove(forwardMostMove) ==
(first.twoMachinesColor[0] == 'w')) {
cps = &first;
} else {
cps = &second;
}
break;
case BeginningOfGame:
default:
return;
}
SendToProgram("?\n", cps);
}
void
TruncateGameEvent ()
{
EditGameEvent();
if (gameMode != EditGame) return;
TruncateGame();
}
void
TruncateGame ()
{
CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
if (forwardMostMove > currentMove) {
if (gameInfo.resultDetails != NULL) {
free(gameInfo.resultDetails);
gameInfo.resultDetails = NULL;
gameInfo.result = GameUnfinished;
}
forwardMostMove = currentMove;
HistorySet(parseList, backwardMostMove, forwardMostMove,
currentMove-1);
}
}
void
HintEvent ()
{
if (appData.noChessProgram) return;
switch (gameMode) {
case MachinePlaysWhite:
if (WhiteOnMove(forwardMostMove)) {
DisplayError(_("Wait until your turn."), 0);
return;
}
break;
case BeginningOfGame:
case MachinePlaysBlack:
if (!WhiteOnMove(forwardMostMove)) {
DisplayError(_("Wait until your turn."), 0);
return;
}
break;
default:
DisplayError(_("No hint available"), 0);
return;
}
SendToProgram("hint\n", &first);
hintRequested = TRUE;
}
int
SaveSelected (FILE *g, int dummy, char *dummy2)
{
ListGame * lg = (ListGame *) gameList.head;
int nItem, cnt=0;
FILE *f;
if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
DisplayError(_("Game list not loaded or empty"), 0);
return 0;
}
creatingBook = TRUE; // suppresses stuff during load game
/* Get list size */
for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
if(lg->position >= 0) { // selected?
LoadGame(f, nItem, "", TRUE);
SaveGamePGN2(g); // leaves g open
cnt++; DoEvents();
}
lg = (ListGame *) lg->node.succ;
}
fclose(g);
creatingBook = FALSE;
return cnt;
}
void
CreateBookEvent ()
{
ListGame * lg = (ListGame *) gameList.head;
FILE *f, *g;
int nItem;
static int secondTime = FALSE;
if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
DisplayError(_("Game list not loaded or empty"), 0);
return;
}
if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
fclose(g);
secondTime++;
DisplayNote(_("Book file exists! Try again for overwrite."));
return;
}
creatingBook = TRUE;
secondTime = FALSE;
/* Get list size */
for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
if(lg->position >= 0) {
LoadGame(f, nItem, "", TRUE);
AddGameToBook(TRUE);
DoEvents();
}
lg = (ListGame *) lg->node.succ;
}
creatingBook = FALSE;
FlushBook();
}
void
BookEvent ()
{
if (appData.noChessProgram) return;
switch (gameMode) {
case MachinePlaysWhite:
if (WhiteOnMove(forwardMostMove)) {
DisplayError(_("Wait until your turn."), 0);
return;
}
break;
case BeginningOfGame:
case MachinePlaysBlack:
if (!WhiteOnMove(forwardMostMove)) {
DisplayError(_("Wait until your turn."), 0);
return;
}
break;
case EditPosition:
EditPositionDone(TRUE);
break;
case TwoMachinesPlay:
return;
default:
break;
}
SendToProgram("bk\n", &first);
bookOutput[0] = NULLCHAR;
bookRequested = TRUE;
}
void
AboutGameEvent ()
{
char *tags = PGNTags(&gameInfo);
TagsPopUp(tags, CmailMsg());
free(tags);
}
/* end button procedures */
void
PrintPosition (FILE *fp, int move)
{
int i, j;
for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
char c = PieceToChar(boards[move][i][j]);
fputc(c == '?' ? '.' : c, fp);
fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
}
}
if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
fprintf(fp, "white to play\n");
else
fprintf(fp, "black to play\n");
}
void
PrintOpponents (FILE *fp)
{
if (gameInfo.white != NULL) {
fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
} else {
fprintf(fp, "\n");
}
}
/* Find last component of program's own name, using some heuristics */
void
TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
{
char *p, *q, c;
int local = (strcmp(host, "localhost") == 0);
while (!local && (p = strchr(prog, ';')) != NULL) {
p++;
while (*p == ' ') p++;
prog = p;
}
if (*prog == '"' || *prog == '\'') {
q = strchr(prog + 1, *prog);
} else {
q = strchr(prog, ' ');
}
if (q == NULL) q = prog + strlen(prog);
p = q;
while (p >= prog && *p != '/' && *p != '\\') p--;
p++;
if(p == prog && *p == '"') p++;
c = *q; *q = 0;
if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
memcpy(buf, p, q - p);
buf[q - p] = NULLCHAR;
if (!local) {
strcat(buf, "@");
strcat(buf, host);
}
}
char *
TimeControlTagValue ()
{
char buf[MSG_SIZ];
if (!appData.clockMode) {
safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
} else if (movesPerSession > 0) {
snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
} else if (timeIncrement == 0) {
snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
} else {
snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
}
return StrSave(buf);
}
void
SetGameInfo ()
{
/* This routine is used only for certain modes */
VariantClass v = gameInfo.variant;
ChessMove r = GameUnfinished;
char *p = NULL;
if(keepInfo) return;
if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
r = gameInfo.result;
p = gameInfo.resultDetails;
gameInfo.resultDetails = NULL;
}
ClearGameInfo(&gameInfo);
gameInfo.variant = v;
switch (gameMode) {
case MachinePlaysWhite:
gameInfo.event = StrSave( appData.pgnEventHeader );
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave(first.tidy);
gameInfo.black = StrSave(UserName());
gameInfo.timeControl = TimeControlTagValue();
break;
case MachinePlaysBlack:
gameInfo.event = StrSave( appData.pgnEventHeader );
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave(UserName());
gameInfo.black = StrSave(first.tidy);
gameInfo.timeControl = TimeControlTagValue();
break;
case TwoMachinesPlay:
gameInfo.event = StrSave( appData.pgnEventHeader );
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
if (roundNr > 0) {
char buf[MSG_SIZ];
snprintf(buf, MSG_SIZ, "%d", roundNr);
gameInfo.round = StrSave(buf);
} else {
gameInfo.round = StrSave("-");
}
if (first.twoMachinesColor[0] == 'w') {
gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
} else {
gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
}
gameInfo.timeControl = TimeControlTagValue();
break;
case EditGame:
gameInfo.event = StrSave("Edited game");
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave("-");
gameInfo.black = StrSave("-");
gameInfo.result = r;
gameInfo.resultDetails = p;
break;
case EditPosition:
gameInfo.event = StrSave("Edited position");
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave("-");
gameInfo.black = StrSave("-");
break;
case IcsPlayingWhite:
case IcsPlayingBlack:
case IcsObserving:
case IcsExamining:
break;
case PlayFromGameFile:
gameInfo.event = StrSave("Game from non-PGN file");
gameInfo.site = StrSave(HostName());
gameInfo.date = PGNDate();
gameInfo.round = StrSave("-");
gameInfo.white = StrSave("?");
gameInfo.black = StrSave("?");
break;
default:
break;
}
}
void
ReplaceComment (int index, char *text)
{
int len;
char *p;
float score;
if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
pvInfoList[index-1].depth == len &&
fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
(p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
while (*text == '\n') text++;
len = strlen(text);
while (len > 0 && text[len - 1] == '\n') len--;
if (commentList[index] != NULL)
free(commentList[index]);
if (len == 0) {
commentList[index] = NULL;
return;
}
if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
*text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
*text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
commentList[index] = (char *) malloc(len + 2);
strncpy(commentList[index], text, len);
commentList[index][len] = '\n';
commentList[index][len + 1] = NULLCHAR;
} else {
// [HGM] braces: if text does not start with known OK delimiter, put braces around it.
char *p;
commentList[index] = (char *) malloc(len + 7);
safeStrCpy(commentList[index], "{\n", 3);
safeStrCpy(commentList[index]+2, text, len+1);
commentList[index][len+2] = NULLCHAR;
while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
strcat(commentList[index], "\n}\n");
}
}
void
CrushCRs (char *text)
{
char *p = text;
char *q = text;
char ch;
do {
ch = *p++;
if (ch == '\r') continue;
*q++ = ch;
} while (ch != '\0');
}
void
AppendComment (int index, char *text, Boolean addBraces)
/* addBraces tells if we should add {} */
{
int oldlen, len;
char *old;
if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
if(addBraces == 3) addBraces = 0; else // force appending literally
text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
CrushCRs(text);
while (*text == '\n') text++;
len = strlen(text);
while (len > 0 && text[len - 1] == '\n') len--;
text[len] = NULLCHAR;
if (len == 0) return;
if (commentList[index] != NULL) {
Boolean addClosingBrace = addBraces;
old = commentList[index];
oldlen = strlen(old);
while(commentList[index][oldlen-1] == '\n')
commentList[index][--oldlen] = NULLCHAR;
commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
safeStrCpy(commentList[index], old, oldlen + len + 6);
free(old);
// [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
while (*text == '\n') { text++; len--; }
commentList[index][--oldlen] = NULLCHAR;
}
if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
else strcat(commentList[index], "\n");
strcat(commentList[index], text);
if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
else strcat(commentList[index], "\n");
} else {
commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
if(addBraces)
safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
else commentList[index][0] = NULLCHAR;
strcat(commentList[index], text);
strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
if(addBraces == TRUE) strcat(commentList[index], "}\n");
}
}
static char *
FindStr (char * text, char * sub_text)
{
char * result = strstr( text, sub_text );
if( result != NULL ) {
result += strlen( sub_text );
}
return result;
}
/* [AS] Try to extract PV info from PGN comment */
/* [HGM] PV time: and then remove it, to prevent it appearing twice */
char *
GetInfoFromComment (int index, char * text)
{
char * sep = text, *p;
if( text != NULL && index > 0 ) {
int score = 0;
int depth = 0;
int time = -1, sec = 0, deci;
char * s_eval = FindStr( text, "[%eval " );
char * s_emt = FindStr( text, "[%emt " );
#if 0
if( s_eval != NULL || s_emt != NULL ) {
#else
if(0) { // [HGM] this code is not finished, and could actually be detrimental
#endif
/* New style */
char delim;
if( s_eval != NULL ) {
if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
return text;
}
if( delim != ']' ) {
return text;
}
}
if( s_emt != NULL ) {
}
return text;
}
else {
/* We expect something like: [+|-]nnn.nn/dd */
int score_lo = 0;
if(*text != '{') return text; // [HGM] braces: must be normal comment
sep = strchr( text, '/' );
if( sep == NULL || sep < (text+4) ) {
return text;
}
p = text;
if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
if(p[1] == '(') { // comment starts with PV
p = strchr(p, ')'); // locate end of PV
if(p == NULL || sep < p+5) return text;
// at this point we have something like "{(.*) +0.23/6 ..."
p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
*p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
// we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
}
time = -1; sec = -1; deci = -1;
if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
return text;
}
if( score_lo < 0 || score_lo >= 100 ) {
return text;
}
if(sec >= 0) time = 600*time + 10*sec; else
if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
/* [HGM] PV time: now locate end of PV info */
while( *++sep >= '0' && *sep <= '9'); // strip depth
if(time >= 0)
while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
if(sec >= 0)
while( *++sep >= '0' && *sep <= '9'); // strip seconds
if(deci >= 0)
while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
}
if( depth <= 0 ) {
return text;
}
if( time < 0 ) {
time = -1;
}
pvInfoList[index-1].depth = depth;
pvInfoList[index-1].score = score;
pvInfoList[index-1].time = 10*time; // centi-sec
if(*sep == '}') *sep = 0; else *--sep = '{';
if(p != text) {
while(*p++ = *sep++)
;
sep = text;
} // squeeze out space between PV and comment, and return both
}
return sep;
}
void
SendToProgram (char *message, ChessProgramState *cps)
{
int count, outCount, error;
char buf[MSG_SIZ];
if (cps->pr == NoProc) return;
Attention(cps);
if (appData.debugMode) {
TimeMark now;
GetTimeMark(&now);
fprintf(debugFP, "%ld >%-6s: %s",
SubtractTimeMarks(&now, &programStartTime),
cps->which, message);
if(serverFP)
fprintf(serverFP, "%ld >%-6s: %s",
SubtractTimeMarks(&now, &programStartTime),
cps->which, message), fflush(serverFP);
}
count = strlen(message);
outCount = OutputToProcess(cps->pr, message, count, &error);
if (outCount < count && !exiting
&& !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
} else {
ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
gameInfo.result = res;
}
gameInfo.resultDetails = StrSave(buf);
}
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
}
}
void
ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
{
char *end_str;
char buf[MSG_SIZ];
ChessProgramState *cps = (ChessProgramState *)closure;
if (isr != cps->isr) return; /* Killed intentionally */
if (count <= 0) {
if (count == 0) {
RemoveInputSource(cps->isr);
snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
_(cps->which), cps->program);
if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
} else {
ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
gameInfo.result = res;
}
gameInfo.resultDetails = StrSave(buf);
}
if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
} else {
snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
_(cps->which), cps->program);
RemoveInputSource(cps->isr);
/* [AS] Program is misbehaving badly... kill it */
if( count == -2 ) {
DestroyChildProcess( cps->pr, 9 );
cps->pr = NoProc;
}
if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
}
return;
}
if ((end_str = strchr(message, '\r')) != NULL)
*end_str = NULLCHAR;
if ((end_str = strchr(message, '\n')) != NULL)
*end_str = NULLCHAR;
if (appData.debugMode) {
TimeMark now; int print = 1;
char *quote = ""; char c; int i;
if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
char start = message[0];
if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
sscanf(message, "hint: %c", &c)!=1 &&
sscanf(message, "pong %c", &c)!=1 && start != '#') {
quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
print = (appData.engineComments >= 2);
}
message[0] = start; // restore original message
}
if(print) {
GetTimeMark(&now);
fprintf(debugFP, "%ld <%-6s: %s%s\n",
SubtractTimeMarks(&now, &programStartTime), cps->which,
quote,
message);
if(serverFP)
fprintf(serverFP, "%ld <%-6s: %s%s\n",
SubtractTimeMarks(&now, &programStartTime), cps->which,
quote,
message), fflush(serverFP);
}
}
/* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
if (appData.icsEngineAnalyze) {
if (strstr(message, "whisper") != NULL ||
strstr(message, "kibitz") != NULL ||
strstr(message, "tellics") != NULL) return;
}
HandleMachineMove(message, cps);
}
void
SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
{
char buf[MSG_SIZ];
int seconds;
if( timeControl_2 > 0 ) {
if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
tc = timeControl_2;
}
}
tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
inc /= cps->timeOdds;
st /= cps->timeOdds;
seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
if (st > 0) {
/* Set exact time per move, normally using st command */
if (cps->stKludge) {
/* GNU Chess 4 has no st command; uses level in a nonstandard way */
seconds = st % 60;
if (seconds == 0) {
snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
} else {
snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
}
} else {
snprintf(buf, MSG_SIZ, "st %d\n", st);
}
} else {
/* Set conventional or incremental time control, using level command */
if (seconds == 0) {
/* Note old gnuchess bug -- minutes:seconds used to not work.
Fixed in later versions, but still avoid :seconds
when seconds is 0. */
snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
} else {
snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
seconds, inc/1000.);
}
}
SendToProgram(buf, cps);
/* Orthoganally (except for GNU Chess 4), limit time to st seconds */
/* Orthogonally, limit search to given depth */
if (sd > 0) {
if (cps->sdKludge) {
snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
} else {
snprintf(buf, MSG_SIZ, "sd %d\n", sd);
}
SendToProgram(buf, cps);
}
if(cps->nps >= 0) { /* [HGM] nps */
if(cps->supportsNPS == FALSE)
cps->nps = -1; // don't use if engine explicitly says not supported!
else {
snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
SendToProgram(buf, cps);
}
}
}
ChessProgramState *
WhitePlayer ()
/* [HGM] return pointer to 'first' or 'second', depending on who plays white */
{
if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
return &second;
return &first;
}
void
SendTimeRemaining (ChessProgramState *cps, int machineWhite)
{
char message[MSG_SIZ];
long time, otime;
/* Note: this routine must be called when the clocks are stopped
or when they have *just* been set or switched; otherwise
it will be off by the time since the current tick started.
*/
if (machineWhite) {
time = whiteTimeRemaining / 10;
otime = blackTimeRemaining / 10;
} else {
time = blackTimeRemaining / 10;
otime = whiteTimeRemaining / 10;
}
/* [HGM] translate opponent's time by time-odds factor */
otime = (otime * cps->other->timeOdds) / cps->timeOdds;
if (time <= 0) time = 1;
if (otime <= 0) otime = 1;
snprintf(message, MSG_SIZ, "time %ld\n", time);
SendToProgram(message, cps);
snprintf(message, MSG_SIZ, "otim %ld\n", otime);
SendToProgram(message, cps);
}
char *
EngineDefinedVariant (ChessProgramState *cps, int n)
{ // return name of n-th unknown variant that engine supports
static char buf[MSG_SIZ];
char *p, *s = cps->variants;
if(!s) return NULL;
do { // parse string from variants feature
VariantClass v;
p = strchr(s, ',');
if(p) *p = NULLCHAR;
v = StringToVariant(s);
if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
!strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
!strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
!strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
}
if(p) *p++ = ',';
if(n < 0) return buf;
} while(s = p);
return NULL;
}
int
BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
{
char buf[MSG_SIZ];
int len = strlen(name);
int val;
if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
(*p) += len + 1;
sscanf(*p, "%d", &val);
*loc = (val != 0);
while (**p && **p != ' ')
(*p)++;
snprintf(buf, MSG_SIZ, "accepted %s\n", name);
SendToProgram(buf, cps);
return TRUE;
}
return FALSE;
}
int
IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
{
char buf[MSG_SIZ];
int len = strlen(name);
if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
(*p) += len + 1;
sscanf(*p, "%d", loc);
while (**p && **p != ' ') (*p)++;
snprintf(buf, MSG_SIZ, "accepted %s\n", name);
SendToProgram(buf, cps);
return TRUE;
}
return FALSE;
}
int
StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
{
char buf[MSG_SIZ];
int len = strlen(name);
if (strncmp((*p), name, len) == 0
&& (*p)[len] == '=' && (*p)[len+1] == '\"') {
(*p) += len + 2;
ASSIGN(*loc, *p); // kludge alert: assign rest of line just to be sure allocation is large enough so that sscanf below always fits
sscanf(*p, "%[^\"]", *loc);
while (**p && **p != '\"') (*p)++;
if (**p == '\"') (*p)++;
snprintf(buf, MSG_SIZ, "accepted %s\n", name);
SendToProgram(buf, cps);
return TRUE;
}
return FALSE;
}
int
ParseOption (Option *opt, ChessProgramState *cps)
// [HGM] options: process the string that defines an engine option, and determine
// name, type, default value, and allowed value range
{
char *p, *q, buf[MSG_SIZ];
int n, min = (-1)<<31, max = 1<<31, def;
opt->target = &opt->value; // OK for spin/slider and checkbox
if(p = strstr(opt->name, " -spin ")) {
if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
if(max < min) max = min; // enforce consistency
if(def < min) def = min;
if(def > max) def = max;
opt->value = def;
opt->min = min;
opt->max = max;
opt->type = Spin;
} else if((p = strstr(opt->name, " -slider "))) {
// for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
if(max < min) max = min; // enforce consistency
if(def < min) def = min;
if(def > max) def = max;
opt->value = def;
opt->min = min;
opt->max = max;
opt->type = Spin; // Slider;
} else if((p = strstr(opt->name, " -string "))) {
opt->textValue = p+9;
opt->type = TextBox;
opt->target = &opt->textValue;
} else if((p = strstr(opt->name, " -file "))) {
// for now -file is a synonym for -string, to already provide compatibility with future polyglots
opt->target = opt->textValue = p+7;
opt->type = FileName; // FileName;
opt->target = &opt->textValue;
} else if((p = strstr(opt->name, " -path "))) {
// for now -file is a synonym for -string, to already provide compatibility with future polyglots
opt->target = opt->textValue = p+7;
opt->type = PathName; // PathName;
opt->target = &opt->textValue;
} else if(p = strstr(opt->name, " -check ")) {
if(sscanf(p, " -check %d", &def) < 1) return FALSE;
opt->value = (def != 0);
opt->type = CheckBox;
} else if(p = strstr(opt->name, " -combo ")) {
opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
if(*q == '*') cps->comboList[cps->comboCnt-1]++;
opt->value = n = 0;
while(q = StrStr(q, " /// ")) {
n++; *q = 0; // count choices, and null-terminate each of them
q += 5;
if(*q == '*') { // remember default, which is marked with * prefix
q++;
opt->value = n;
}
cps->comboList[cps->comboCnt++] = q;
}
cps->comboList[cps->comboCnt++] = NULL;
opt->max = n + 1;
opt->type = ComboBox;
} else if(p = strstr(opt->name, " -button")) {
opt->type = Button;
} else if(p = strstr(opt->name, " -save")) {
opt->type = SaveButton;
} else return FALSE;
*p = 0; // terminate option name
// now look if the command-line options define a setting for this engine option.
if(cps->optionSettings && cps->optionSettings[0])
p = strstr(cps->optionSettings, opt->name); else p = NULL;
if(p && (p == cps->optionSettings || p[-1] == ',')) {
snprintf(buf, MSG_SIZ, "option %s", p);
if(p = strstr(buf, ",")) *p = 0;
if(q = strchr(buf, '=')) switch(opt->type) {
case ComboBox:
for(n=0; n<opt->max; n++)
if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
break;
case TextBox:
safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
break;
case Spin:
case CheckBox:
opt->value = atoi(q+1);
default:
break;
}
strcat(buf, "\n");
SendToProgram(buf, cps);
}
return TRUE;
}
void
FeatureDone (ChessProgramState *cps, int val)
{
DelayedEventCallback cb = GetDelayedEvent();
if ((cb == InitBackEnd3 && cps == &first) ||
(cb == SettingsMenuIfReady && cps == &second) ||
(cb == LoadEngine) ||
(cb == TwoMachinesEventIfReady)) {
CancelDelayedEvent();
ScheduleDelayedEvent(cb, val ? 1 : 3600000);
} else if(!val && !cps->reload) ClearOptions(cps); // let 'spurious' done=0 clear engine's option list
cps->initDone = val;
if(val) cps->reload = FALSE, RefreshSettingsDialog(cps, val);
}
/* Parse feature command from engine */
void
ParseFeatures (char *args, ChessProgramState *cps)
{
char *p = args;
char *q = NULL;
int val;
char buf[MSG_SIZ];
for (;;) {
while (*p == ' ') p++;
if (*p == NULLCHAR) return;
if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
if (BoolFeature(&p, "reuse", &val, cps)) {
/* Engine can disable reuse, but can't enable it if user said no */
if (!val) cps->reuse = FALSE;
continue;
}
if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
if (StringFeature(&p, "myname", &cps->tidy, cps)) {
if (gameMode == TwoMachinesPlay) {
DisplayTwoMachinesTitle();
} else {
DisplayTitle("");
}
continue;
}
if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
if (IntFeature(&p, "done", &val, cps)) {
FeatureDone(cps, val);
continue;
}
/* Added by Tord: */
if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
/* End of additions by Tord */
/* [HGM] added features: */
if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
FREE(cps->option[cps->nrOptions].name);
cps->option[cps->nrOptions].name = q; q = NULL;
if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
SendToProgram(buf, cps);
continue;
}
if(cps->nrOptions >= MAX_OPTIONS) {
cps->nrOptions--;
snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
DisplayError(buf, 0);
}
continue;
}
/* End of additions by HGM */
/* unknown feature: complain and skip */
q = p;
while (*q && *q != '=') q++;
snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
SendToProgram(buf, cps);
p = q;
if (*p == '=') {
p++;
if (*p == '\"') {
p++;
while (*p && *p != '\"') p++;
if (*p == '\"') p++;
} else {
while (*p && *p != ' ') p++;
}
}
}
}
void
PeriodicUpdatesEvent (int newState)
{
if (newState == appData.periodicUpdates)
return;
appData.periodicUpdates=newState;
/* Display type changes, so update it now */
// DisplayAnalysis();
/* Get the ball rolling again... */
if (newState) {
AnalysisPeriodicEvent(1);
StartAnalysisClock();
}
}
void
PonderNextMoveEvent (int newState)
{
if (newState == appData.ponderNextMove) return;
if (gameMode == EditPosition) EditPositionDone(TRUE);
if (newState) {
SendToProgram("hard\n", &first);
if (gameMode == TwoMachinesPlay) {
SendToProgram("hard\n", &second);
}
} else {
SendToProgram("easy\n", &first);
thinkOutput[0] = NULLCHAR;
if (gameMode == TwoMachinesPlay) {
SendToProgram("easy\n", &second);
}
}
appData.ponderNextMove = newState;
}
void
NewSettingEvent (int option, int *feature, char *command, int value)
{
char buf[MSG_SIZ];
if (gameMode == EditPosition) EditPositionDone(TRUE);
snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
if(feature == NULL || *feature) SendToProgram(buf, &first);
if (gameMode == TwoMachinesPlay) {
if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
}
}
void
ShowThinkingEvent ()
// [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
{
static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
int newState = appData.showThinking
// [HGM] thinking: other features now need thinking output as well
|| !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
if (oldState == newState) return;
oldState = newState;
if (gameMode == EditPosition) EditPositionDone(TRUE);
if (oldState) {
SendToProgram("post\n", &first);
if (gameMode == TwoMachinesPlay) {
SendToProgram("post\n", &second);
}
} else {
SendToProgram("nopost\n", &first);
thinkOutput[0] = NULLCHAR;
if (gameMode == TwoMachinesPlay) {
SendToProgram("nopost\n", &second);
}
}
// appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
}
void
AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
{
ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
if (pr == NoProc) return;
AskQuestion(title, question, replyPrefix, pr);
}
void
TypeInEvent (char firstChar)
{
if ((gameMode == BeginningOfGame && !appData.icsActive) ||
gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
gameMode == AnalyzeMode || gameMode == EditGame ||
gameMode == EditPosition || gameMode == IcsExamining ||
gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
gameMode == Training) PopUpMoveDialog(firstChar);
}
void
TypeInDoneEvent (char *move)
{
Board board;
int n, fromX, fromY, toX, toY;
char promoChar;
ChessMove moveType;
// [HGM] FENedit
if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
EditPositionPasteFEN(move);
return;
}
// [HGM] movenum: allow move number to be typed in any mode
if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
ToNrEvent(2*n-1);
return;
}
// undocumented kludge: allow command-line option to be typed in!
// (potentially fatal, and does not implement the effect of the option.)
// should only be used for options that are values on which future decisions will be made,
// and definitely not on options that would be used during initialization.
if(strstr(move, "!!! -") == move) {
ParseArgsFromString(move+4);
return;
}
if (gameMode != EditGame && currentMove != forwardMostMove &&
gameMode != Training) {
DisplayMoveError(_("Displayed move is not current"));
} else {
int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
&moveType, &fromX, &fromY, &toX, &toY, &promoChar);
if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
&moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
UserMoveEvent(fromX, fromY, toX, toY, promoChar);
} else {
DisplayMoveError(_("Could not parse move"));
}
}
}
void
DisplayMove (int moveNumber)
{
char message[MSG_SIZ];
char res[MSG_SIZ];
char cpThinkOutput[MSG_SIZ];
if(appData.noGUI) return; // [HGM] fast: suppress display of moves
if (moveNumber == forwardMostMove - 1 ||
gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
if (strchr(cpThinkOutput, '\n')) {
*strchr(cpThinkOutput, '\n') = NULLCHAR;
}
} else {
*cpThinkOutput = NULLCHAR;
}
/* [AS] Hide thinking from human user */
if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
*cpThinkOutput = NULLCHAR;
if( thinkOutput[0] != NULLCHAR ) {
int i;
for( i=0; i<=hiddenThinkOutputState; i++ ) {
cpThinkOutput[i] = '.';
}
cpThinkOutput[i] = NULLCHAR;
hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
}
}
if (moveNumber == forwardMostMove - 1 &&
gameInfo.resultDetails != NULL) {
if (gameInfo.resultDetails[0] == NULLCHAR) {
snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
} else {
snprintf(res, MSG_SIZ, " {%s} %s",
T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
}
} else {
res[0] = NULLCHAR;
}
if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
DisplayMessage(res, cpThinkOutput);
} else {
snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
WhiteOnMove(moveNumber) ? " " : ".. ",
parseList[moveNumber], res);
DisplayMessage(message, cpThinkOutput);
}
}
void
DisplayComment (int moveNumber, char *text)
{
char title[MSG_SIZ];
if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
} else {
snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
WhiteOnMove(moveNumber) ? " " : ".. ",
parseList[moveNumber]);
}
if (text != NULL && (appData.autoDisplayComment || commentUp))
CommentPopUp(title, text);
}
/* This routine sends a ^C interrupt to gnuchess, to awaken it if it
* might be busy thinking or pondering. It can be omitted if your
* gnuchess is configured to stop thinking immediately on any user
* input. However, that gnuchess feature depends on the FIONREAD
* ioctl, which does not work properly on some flavors of Unix.
*/
void
Attention (ChessProgramState *cps)
{
#if ATTENTION
if (!cps->useSigint) return;
if (appData.noChessProgram || (cps->pr == NoProc)) return;
switch (gameMode) {
case MachinePlaysWhite:
case MachinePlaysBlack:
case TwoMachinesPlay:
case IcsPlayingWhite:
case IcsPlayingBlack:
case AnalyzeMode:
case AnalyzeFile:
/* Skip if we know it isn't thinking */
if (!cps->maybeThinking) return;
if (appData.debugMode)
fprintf(debugFP, "Interrupting %s\n", cps->which);
InterruptChildProcess(cps->pr);
cps->maybeThinking = FALSE;
break;
default:
break;
}
#endif /*ATTENTION*/
}
int
CheckFlags ()
{
if (whiteTimeRemaining <= 0) {
if (!whiteFlag) {
whiteFlag = TRUE;
if (appData.icsActive) {
if (appData.autoCallFlag &&
gameMode == IcsPlayingBlack && !blackFlag) {
SendToICS(ics_prefix);
SendToICS("flag\n");
}
} else {
if (blackFlag) {
if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
} else {
if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
if (appData.autoCallFlag) {
GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
return TRUE;
}
}
}
}
}
if (blackTimeRemaining <= 0) {
if (!blackFlag) {
blackFlag = TRUE;
if (appData.icsActive) {
if (appData.autoCallFlag &&
gameMode == IcsPlayingWhite && !whiteFlag) {
SendToICS(ics_prefix);
SendToICS("flag\n");
}
} else {
if (whiteFlag) {
if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
} else {
if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
if (appData.autoCallFlag) {
GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
return TRUE;
}
}
}
}
}
return FALSE;
}
void
CheckTimeControl ()
{
if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
gameMode == PlayFromGameFile || forwardMostMove == 0) return;
/*
* add time to clocks when time control is achieved ([HGM] now also used for increment)
*/
if ( !WhiteOnMove(forwardMostMove) ) {
/* White made time control */
lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
/* [HGM] time odds: correct new time quota for time odds! */
/ WhitePlayer()->timeOdds;
lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
} else {
lastBlack -= blackTimeRemaining;
/* Black made time control */
blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
/ WhitePlayer()->other->timeOdds;
lastWhite = whiteTimeRemaining;
}
}
void
DisplayBothClocks ()
{
int wom = gameMode == EditPosition ?
!blackPlaysFirst : WhiteOnMove(currentMove);
DisplayWhiteClock(whiteTimeRemaining, wom);
DisplayBlackClock(blackTimeRemaining, !wom);
}
/* Timekeeping seems to be a portability nightmare. I think everyone
has ftime(), but I'm really not sure, so I'm including some ifdefs
to use other calls if you don't. Clocks will be less accurate if
you have neither ftime nor gettimeofday.
*/
/* VS 2008 requires the #include outside of the function */
#if !HAVE_GETTIMEOFDAY && HAVE_FTIME
#include <sys/timeb.h>
#endif
/* Get the current time as a TimeMark */
void
GetTimeMark (TimeMark *tm)
{
#if HAVE_GETTIMEOFDAY
struct timeval timeVal;
struct timezone timeZone;
gettimeofday(&timeVal, &timeZone);
tm->sec = (long) timeVal.tv_sec;
tm->ms = (int) (timeVal.tv_usec / 1000L);
#else /*!HAVE_GETTIMEOFDAY*/
#if HAVE_FTIME
// include <sys/timeb.h> / moved to just above start of function
struct timeb timeB;
ftime(&timeB);
tm->sec = (long) timeB.time;
tm->ms = (int) timeB.millitm;
#else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
tm->sec = (long) time(NULL);
tm->ms = 0;
#endif
#endif
}
/* Return the difference in milliseconds between two
time marks. We assume the difference will fit in a long!
*/
long
SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
{
return 1000L*(tm2->sec - tm1->sec) +
(long) (tm2->ms - tm1->ms);
}
/*
* Code to manage the game clocks.
*
* In tournament play, black starts the clock and then white makes a move.
* We give the human user a slight advantage if he is playing white---the
* clocks don't run until he makes his first move, so it takes zero time.
* Also, we don't account for network lag, so we could get out of sync
* with GNU Chess's clock -- but then, referees are always right.
*/
static TimeMark tickStartTM;
static long intendedTickLength;
long
NextTickLength (long timeRemaining)
{
long nominalTickLength, nextTickLength;
if (timeRemaining > 0L && timeRemaining <= 10000L)
nominalTickLength = 100L;
else
nominalTickLength = 1000L;
nextTickLength = timeRemaining % nominalTickLength;
if (nextTickLength <= 0) nextTickLength += nominalTickLength;
return nextTickLength;
}
/* Adjust clock one minute up or down */
void
AdjustClock (Boolean which, int dir)
{
if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
if(which) blackTimeRemaining += 60000*dir;
else whiteTimeRemaining += 60000*dir;
DisplayBothClocks();
adjustedClock = TRUE;
}
/* Stop clocks and reset to a fresh time control */
void
ResetClocks ()
{
(void) StopClockTimer();
if (appData.icsActive) {
whiteTimeRemaining = blackTimeRemaining = 0;
} else if (searchTime) {
whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
} else { /* [HGM] correct new time quote for time odds */
whiteTC = blackTC = fullTimeControlString;
whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
}
if (whiteFlag || blackFlag) {
DisplayTitle("");
whiteFlag = blackFlag = FALSE;
}
lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
DisplayBothClocks();
adjustedClock = FALSE;
}
#define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
static int timeSuffix; // [HGM] This should realy be a passed parameter, but it has to pass through too many levels for my laziness...
/* Decrement running clock by amount of time that has passed */
void
DecrementClocks ()
{
long tRemaining;
long lastTickLength, fudge;
TimeMark now;
if (!appData.clockMode) return;
if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
GetTimeMark(&now);
lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
/* Fudge if we woke up a little too soon */
fudge = intendedTickLength - lastTickLength;
if (fudge < 0 || fudge > FUDGE) fudge = 0;
if (WhiteOnMove(forwardMostMove)) {
if(whiteNPS >= 0) lastTickLength = 0;
tRemaining = whiteTimeRemaining -= lastTickLength;
if( tRemaining < 0 && !appData.icsActive) {
GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
whiteStartMove = forwardMostMove; whiteTC = nextSession;
lastWhite= tRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
}
}
if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[0][forwardMostMove-1] - tRemaining;
DisplayWhiteClock(whiteTimeRemaining - fudge,
WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
timeSuffix = 0;
} else {
if(blackNPS >= 0) lastTickLength = 0;
tRemaining = blackTimeRemaining -= lastTickLength;
if( tRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
if(suddenDeath) {
blackStartMove = forwardMostMove;
lastBlack = tRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
}
}
if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[1][forwardMostMove-1] - tRemaining;
DisplayBlackClock(blackTimeRemaining - fudge,
!WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
timeSuffix = 0;
}
if (CheckFlags()) return;
if(twoBoards) { // count down secondary board's clocks as well
activePartnerTime -= lastTickLength;
partnerUp = 1;
if(activePartner == 'W')
DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
else
DisplayBlackClock(activePartnerTime, TRUE);
partnerUp = 0;
}
tickStartTM = now;
intendedTickLength = NextTickLength( tRemaining - fudge) + fudge;
StartClockTimer(intendedTickLength);
/* if the time remaining has fallen below the alarm threshold, sound the
* alarm. if the alarm has sounded and (due to a takeback or time control
* with increment) the time remaining has increased to a level above the
* threshold, reset the alarm so it can sound again.
*/
if (appData.icsActive && appData.icsAlarm) {
/* make sure we are dealing with the user's clock */
if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
)) return;
if (alarmSounded && ( tRemaining > appData.icsAlarmTime)) {
alarmSounded = FALSE;
} else if (!alarmSounded && ( tRemaining <= appData.icsAlarmTime)) {
PlayAlarmSound();
alarmSounded = TRUE;
}
}
}
/* A player has just moved, so stop the previously running
clock and (if in clock mode) start the other one.
We redisplay both clocks in case we're in ICS mode, because
ICS gives us an update to both clocks after every move.
Note that this routine is called *after* forwardMostMove
is updated, so the last fractional tick must be subtracted
from the color that is *not* on move now.
*/
void
SwitchClocks (int newMoveNr)
{
long lastTickLength;
TimeMark now;
int flagged = FALSE;
GetTimeMark(&now);
if (StopClockTimer() && appData.clockMode) {
lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
if (!WhiteOnMove(forwardMostMove)) {
if(blackNPS >= 0) lastTickLength = 0;
blackTimeRemaining -= lastTickLength;
/* [HGM] PGNtime: save time for PGN file if engine did not give it */
// if(pvInfoList[forwardMostMove].time == -1)
pvInfoList[forwardMostMove].time = // use GUI time
(timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
} else {
if(whiteNPS >= 0) lastTickLength = 0;
whiteTimeRemaining -= lastTickLength;
/* [HGM] PGNtime: save time for PGN file if engine did not give it */
// if(pvInfoList[forwardMostMove].time == -1)
pvInfoList[forwardMostMove].time =
(timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
}
flagged = CheckFlags();
}
forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
CheckTimeControl();
if (flagged || !appData.clockMode) return;
switch (gameMode) {
case MachinePlaysBlack:
case MachinePlaysWhite:
case BeginningOfGame:
if (pausing) return;
break;
case EditGame:
case PlayFromGameFile:
case IcsExamining:
return;
default:
break;
}
if (searchTime) { // [HGM] st: set clock of player that has to move to max time
if(WhiteOnMove(forwardMostMove))
whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
}
tickStartTM = now;
intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
whiteTimeRemaining : blackTimeRemaining);
StartClockTimer(intendedTickLength);
}
/* Stop both clocks */
void
StopClocks ()
{
long lastTickLength;
TimeMark now;
if (!StopClockTimer()) return;
if (!appData.clockMode) return;
GetTimeMark(&now);
lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
if (WhiteOnMove(forwardMostMove)) {
if(whiteNPS >= 0) lastTickLength = 0;
whiteTimeRemaining -= lastTickLength;
DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
} else {
if(blackNPS >= 0) lastTickLength = 0;
blackTimeRemaining -= lastTickLength;
DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
}
CheckFlags();
}
/* Start clock of player on move. Time may have been reset, so
if clock is already running, stop and restart it. */
void
StartClocks ()
{
(void) StopClockTimer(); /* in case it was running already */
DisplayBothClocks();
if (CheckFlags()) return;
if (!appData.clockMode) return;
if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
GetTimeMark(&tickStartTM);
intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
whiteTimeRemaining : blackTimeRemaining);
/* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
whiteNPS = blackNPS = -1;
if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
|| appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
whiteNPS = first.nps;
if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
|| appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
blackNPS = first.nps;
if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
whiteNPS = second.nps;
if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
blackNPS = second.nps;
if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
StartClockTimer(intendedTickLength);
}
char *
TimeString (long ms)
{
long second, minute, hour, day;
char *sign = "";
static char buf[40], moveTime[8];
if (ms > 0 && ms <= 9900) {
/* convert milliseconds to tenths, rounding up */
double tenths = floor( ((double)(ms + 99L)) / 100.00 );
snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
return buf;
}
/* convert milliseconds to seconds, rounding up */
/* use floating point to avoid strangeness of integer division
with negative dividends on many machines */
second = (long) floor(((double) (ms + 999L)) / 1000.0);
if (second < 0) {
sign = "-";
second = -second;
}
day = second / (60 * 60 * 24);
second = second % (60 * 60 * 24);
hour = second / (60 * 60);
second = second % (60 * 60);
minute = second / 60;
second = second % 60;
if(timeSuffix) snprintf(moveTime, 8, " (%d)", timeSuffix/1000); // [HGM] kludge alert; fraction contains move time
else *moveTime = NULLCHAR;
if (day > 0)
snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld%s ",
sign, day, hour, minute, second, moveTime);
else if (hour > 0)
snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld%s ", sign, hour, minute, second, moveTime);
else
snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld%s ", sign, minute, second, moveTime);
return buf;
}
/*
* This is necessary because some C libraries aren't ANSI C compliant yet.
*/
char *
StrStr (char *string, char *match)
{
int i, length;
length = strlen(match);
for (i = strlen(string) - length; i >= 0; i--, string++)
if (!strncmp(match, string, length))
return string;
return NULL;
}
char *
StrCaseStr (char *string, char *match)
{
int i, j, length;
length = strlen(match);
for (i = strlen(string) - length; i >= 0; i--, string++) {
for (j = 0; j < length; j++) {
if (ToLower(match[j]) != ToLower(string[j]))
break;
}
if (j == length) return string;
}
return NULL;
}
#ifndef _amigados
int
StrCaseCmp (char *s1, char *s2)
{
char c1, c2;
for (;;) {
c1 = ToLower(*s1++);
c2 = ToLower(*s2++);
if (c1 > c2) return 1;
if (c1 < c2) return -1;
if (c1 == NULLCHAR) return 0;
}
}
int
ToLower (int c)
{
return isupper(c) ? tolower(c) : c;
}
int
ToUpper (int c)
{
return islower(c) ? toupper(c) : c;
}
#endif /* !_amigados */
char *
StrSave (char *s)
{
char *ret;
if ((ret = (char *) malloc(strlen(s) + 1)))
{
safeStrCpy(ret, s, strlen(s)+1);
}
return ret;
}
char *
StrSavePtr (char *s, char **savePtr)
{
if (*savePtr) {
free(*savePtr);
}
if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
safeStrCpy(*savePtr, s, strlen(s)+1);
}
return(*savePtr);
}
char *
PGNDate ()
{
time_t clock;
struct tm *tm;
char buf[MSG_SIZ];
clock = time((time_t *)NULL);
tm = localtime(&clock);
snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
return StrSave(buf);
}
char *
PositionToFEN (int move, char *overrideCastling, int moveCounts)
{
int i, j, fromX, fromY, toX, toY;
int whiteToPlay, haveRights = nrCastlingRights;
char buf[MSG_SIZ];
char *p, *q;
int emptycount;
ChessSquare piece;
whiteToPlay = (gameMode == EditPosition) ?
!blackPlaysFirst : (move % 2 == 0);
p = buf;
/* Piece placement data */
for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
emptycount = 0;
for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
if (boards[move][i][j] == EmptySquare) {
emptycount++;
} else { ChessSquare piece = boards[move][i][j];
if (emptycount > 0) {
if(emptycount<10) /* [HGM] can be >= 10 */
*p++ = '0' + emptycount;
else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
emptycount = 0;
}
if(PieceToChar(piece) == '+') {
/* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
*p++ = '+';
piece = (ChessSquare)(CHUDEMOTED(piece));
}
*p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
if(*p = PieceSuffix(piece)) p++;
if(p[-1] == '~') {
/* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED(piece)));
*p++ = '~';
}
}
}
if (emptycount > 0) {
if(emptycount<10) /* [HGM] can be >= 10 */
*p++ = '0' + emptycount;
else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
emptycount = 0;
}
*p++ = '/';
}
*(p - 1) = ' ';
/* [HGM] print Crazyhouse or Shogi holdings */
if( gameInfo.holdingsWidth ) {
*(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
q = p;
for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
piece = boards[move][i][BOARD_WIDTH-1];
if( piece != EmptySquare )
for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
*p++ = PieceToChar(piece);
}
for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
piece = boards[move][BOARD_HEIGHT-i-1][0];
if( piece != EmptySquare )
for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
*p++ = PieceToChar(piece);
}
if( q == p ) *p++ = '-';
*p++ = ']';
*p++ = ' ';
}
/* Active color */
*p++ = whiteToPlay ? 'w' : 'b';
*p++ = ' ';
if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
haveRights = 0; q = p;
for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
piece = boards[move][0][i];
if(piece >= WhitePawn && piece <= WhiteKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
if(!(boards[move][TOUCHED_W] & 1<<i)) *p++ = 'A' + i; // print file ID if it has not moved
}
}
for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
piece = boards[move][BOARD_HEIGHT-1][i];
if(piece >= BlackPawn && piece <= BlackKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
if(!(boards[move][TOUCHED_B] & 1<<i)) *p++ = 'a' + i; // print file ID if it has not moved
}
}
if(p == q) *p++ = '-';
*p++ = ' ';
}
if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
while(*p++ = *q++)
;
if(q != overrideCastling+1) p[-1] = ' '; else --p;
} else {
if(haveRights) {
int handW=0, handB=0;
if(gameInfo.variant == VariantSChess) { // for S-Chess, all virgin backrank pieces must be listed
for(i=0; i<BOARD_HEIGHT; i++) handW += boards[move][i][BOARD_RGHT]; // count white held pieces
for(i=0; i<BOARD_HEIGHT; i++) handB += boards[move][i][BOARD_LEFT-1]; // count black held pieces
}
q = p;
if(appData.fischerCastling) {
if(handW) { // in shuffle S-Chess simply dump all virgin pieces
for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
if(boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
} else {
/* [HGM] write directly from rights */
if(boards[move][CASTLING][2] != NoRights &&
boards[move][CASTLING][0] != NoRights )
*p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
if(boards[move][CASTLING][2] != NoRights &&
boards[move][CASTLING][1] != NoRights )
*p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
}
if(handB) {
for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
if(boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
} else {
if(boards[move][CASTLING][5] != NoRights &&
boards[move][CASTLING][3] != NoRights )
*p++ = boards[move][CASTLING][3] + AAA;
if(boards[move][CASTLING][5] != NoRights &&
boards[move][CASTLING][4] != NoRights )
*p++ = boards[move][CASTLING][4] + AAA;
}
} else {
/* [HGM] write true castling rights */
if( nrCastlingRights == 6 ) {
int q, k=0;
if(boards[move][CASTLING][0] != NoRights &&
boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
q = (boards[move][CASTLING][1] != NoRights &&
boards[move][CASTLING][2] != NoRights );
if(handW) { // for S-Chess with pieces in hand, list virgin pieces between K and Q
for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
if((boards[move][0][i] != WhiteKing || k+q == 0) &&
boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
}
if(q) *p++ = 'Q';
k = 0;
if(boards[move][CASTLING][3] != NoRights &&
boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
q = (boards[move][CASTLING][4] != NoRights &&
boards[move][CASTLING][5] != NoRights );
if(handB) {
for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
}
if(q) *p++ = 'q';
}
}
if (q == p) *p++ = '-'; /* No castling rights */
*p++ = ' ';
}
if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
/* En passant target square */
if (move > backwardMostMove) {
fromX = moveList[move - 1][0] - AAA;
fromY = moveList[move - 1][1] - ONE;
toX = moveList[move - 1][2] - AAA;
toY = moveList[move - 1][3] - ONE;
if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
fromX == toX) {
/* 2-square pawn move just happened */
*p++ = toX + AAA;
*p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
} else {
*p++ = '-';
}
} else if(move == backwardMostMove) {
// [HGM] perhaps we should always do it like this, and forget the above?
if((signed char)boards[move][EP_STATUS] >= 0) {
*p++ = boards[move][EP_STATUS] + AAA;
*p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
} else {
*p++ = '-';
}
} else {
*p++ = '-';
}
*p++ = ' ';
}
}
if(moveCounts)
{ int i = 0, j=move;
/* [HGM] find reversible plies */
if (appData.debugMode) { int k;
fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
for(k=backwardMostMove; k<=forwardMostMove; k++)
fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
}
while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
if( j == backwardMostMove ) i += initialRulePlies;
sprintf(p, "%d ", i);
p += i>=100 ? 4 : i >= 10 ? 3 : 2;
/* Fullmove number */
sprintf(p, "%d", (move / 2) + 1);
} else *--p = NULLCHAR;
return StrSave(buf);
}
Boolean
ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
{
int i, j, k, w=0, subst=0, shuffle=0, wKingRank = -1, bKingRank = -1;
char *p, c;
int emptycount, virgin[BOARD_FILES];
ChessSquare piece, king = (gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing);
p = fen;
for(i=1; i<=deadRanks; i++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) board[BOARD_HEIGHT-i][j] = DarkSquare;
/* Piece placement data */
for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
j = 0;
for (;;) {
if (*p == '/' || *p == ' ' || *p == '[' ) {
if(j > w) w = j;
emptycount = gameInfo.boardWidth - j;
while (emptycount--)
board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
if (*p == '/') p++;
else if(autoSize && i != BOARD_HEIGHT-1) { // we stumbled unexpectedly into end of board
for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
}
appData.NrRanks = gameInfo.boardHeight - i; i=0;
}
break;
#if(BOARD_FILES >= 10)*0
} else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
p++; emptycount=10;
if (j + emptycount > gameInfo.boardWidth) return FALSE;
while (emptycount--)
board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
#endif
} else if (*p == '*') {
board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
} else if (isdigit(*p)) {
emptycount = *p++ - '0';
while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
if (j + emptycount > gameInfo.boardWidth) return FALSE;
while (emptycount--)
board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
} else if (*p == '<') {
if(i == BOARD_HEIGHT-1) shuffle = 1;
else if (i != 0 || !shuffle) return FALSE;
p++;
} else if (shuffle && *p == '>') {
p++; // for now ignore closing shuffle range, and assume rank-end
} else if (*p == '?') {
if (j >= gameInfo.boardWidth) return FALSE;
if (i != 0 && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
} else if (*p == '+' || isalpha(*p)) {
char *q, *s = SUFFIXES;
if (j >= gameInfo.boardWidth) return FALSE;
if(*p=='+') {
char c = *++p;
if(q = strchr(s, p[1])) p++;
piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
if(piece == EmptySquare) return FALSE; /* unknown piece */
piece = (ChessSquare) (CHUPROMOTED(piece)); p++;
if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
} else {
char c = *p++;
if(q = strchr(s, *p)) p++;
piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
}
if(piece==EmptySquare) return FALSE; /* unknown piece */
if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
piece = (ChessSquare) (PROMOTED(piece));
if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
p++;
}
board[i][(j++)+gameInfo.holdingsWidth] = piece;
if(piece == king) wKingRank = i;
if(piece == WHITE_TO_BLACK king) bKingRank = i;
} else {
return FALSE;
}
}
}
while (*p == '/' || *p == ' ') p++;
if(autoSize && w != 0) appData.NrFiles = w, InitPosition(TRUE);
/* [HGM] by default clear Crazyhouse holdings, if present */
if(gameInfo.holdingsWidth) {
for(i=0; i<BOARD_HEIGHT; i++) {
board[i][0] = EmptySquare; /* black holdings */
board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
board[i][1] = (ChessSquare) 0; /* black counts */
board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
}
}
/* [HGM] look for Crazyhouse holdings here */
while(*p==' ') p++;
if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
int swap=0, wcnt=0, bcnt=0;
if(*p == '[') p++;
if(*p == '<') swap++, p++;
if(*p == '-' ) p++; /* empty holdings */ else {
if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
/* if we would allow FEN reading to set board size, we would */
/* have to add holdings and shift the board read so far here */
while( (piece = CharToPiece(*p) ) != EmptySquare ) {
p++;
if((int) piece >= (int) BlackPawn ) {
i = (int)piece - (int)BlackPawn;
i = PieceToNumber((ChessSquare)i);
if( i >= gameInfo.holdingsSize ) return FALSE;
board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
board[BOARD_HEIGHT-1-i][1]++; /* black counts */
bcnt++;
} else {
i = (int)piece - (int)WhitePawn;
i = PieceToNumber((ChessSquare)i);
if( i >= gameInfo.holdingsSize ) return FALSE;
board[i][BOARD_WIDTH-1] = piece; /* white holdings */
board[i][BOARD_WIDTH-2]++; /* black holdings */
wcnt++;
}
}
if(subst) { // substitute back-rank question marks by holdings pieces
for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
int k, m, n = bcnt + 1;
if(board[0][j] == ClearBoard) {
if(!wcnt) return FALSE;
n = rand() % wcnt;
for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
break;
}
}
if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
if(!bcnt) return FALSE;
if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[BOARD_HEIGHT-1-k][1]) < 0) {
board[BOARD_HEIGHT-1][j] = board[BOARD_HEIGHT-1-k][0]; bcnt--;
if(--board[BOARD_HEIGHT-1-k][1] == 0) board[BOARD_HEIGHT-1-k][0] = EmptySquare;
break;
}
}
}
subst = 0;
}
}
if(*p == ']') p++;
}
if(subst) return FALSE; // substitution requested, but no holdings
while(*p == ' ') p++;
/* Active color */
c = *p++;
if(appData.colorNickNames) {
if( c == appData.colorNickNames[0] ) c = 'w'; else
if( c == appData.colorNickNames[1] ) c = 'b';
}
switch (c) {
case 'w':
*blackPlaysFirst = FALSE;
break;
case 'b':
*blackPlaysFirst = TRUE;
break;
default:
return FALSE;
}
/* [HGM] We NO LONGER ignore the rest of the FEN notation */
/* return the extra info in global variiables */
while(*p==' ') p++;
if(!isdigit(*p) && *p != '-') { // we seem to have castling rights. Make sure they are on the rank the King actually is.
if(wKingRank >= 0) for(i=0; i<3; i++) castlingRank[i] = wKingRank;
if(bKingRank >= 0) for(i=3; i<6; i++) castlingRank[i] = bKingRank;
}
/* set defaults in case FEN is incomplete */
board[EP_STATUS] = EP_UNKNOWN;
board[TOUCHED_W] = board[TOUCHED_B] = 0;
for(i=0; i<nrCastlingRights; i++ ) {
board[CASTLING][i] =
appData.fischerCastling ? NoRights : initialRights[i];
} /* assume possible unless obviously impossible */
if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
&& board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
&& board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
FENrulePlies = 0;
if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
char *q = p;
int w=0, b=0;
while(isalpha(*p)) {
if(isupper(*p)) w |= 1 << (*p++ - 'A');
if(islower(*p)) b |= 1 << (*p++ - 'a');
}
if(*p == '-') p++;
if(p != q) {
board[TOUCHED_W] = ~w;
board[TOUCHED_B] = ~b;
while(*p == ' ') p++;
}
} else
if(nrCastlingRights) {
int fischer = 0;
if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
/* castling indicator present, so default becomes no castlings */
for(i=0; i<nrCastlingRights; i++ ) {
board[CASTLING][i] = NoRights;
}
}
while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
(appData.fischerCastling || gameInfo.variant == VariantSChess) &&
( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
if(board[castlingRank[5]][i] == BlackKing) blackKingFile = i;
if(board[castlingRank[2]][i] == WhiteKing) whiteKingFile = i;
}
if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
if(whiteKingFile == NoRights || board[castlingRank[2]][whiteKingFile] != WhiteUnicorn
&& board[castlingRank[2]][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
if(blackKingFile == NoRights || board[castlingRank[5]][blackKingFile] != BlackUnicorn
&& board[castlingRank[5]][blackKingFile] != BlackKing) blackKingFile = NoRights;
switch(c) {
case'K':
for(i=BOARD_RGHT-1; board[castlingRank[2]][i]!=WhiteRook && i>whiteKingFile; i--);
board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
board[CASTLING][2] = whiteKingFile;
if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
break;
case'Q':
for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[2]][i]!=WhiteRook && i<whiteKingFile; i++);
board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
board[CASTLING][2] = whiteKingFile;
if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
break;
case'k':
for(i=BOARD_RGHT-1; board[castlingRank[5]][i]!=BlackRook && i>blackKingFile; i--);
board[CASTLING][3] = i != blackKingFile ? i : NoRights;
board[CASTLING][5] = blackKingFile;
if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
break;
case'q':
for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[5]][i]!=BlackRook && i<blackKingFile; i++);
board[CASTLING][4] = i != blackKingFile ? i : NoRights;
board[CASTLING][5] = blackKingFile;
if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
case '-':
break;
default: /* FRC castlings */
if(c >= 'a') { /* black rights */
if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
if(i == BOARD_RGHT) break;
board[CASTLING][5] = i;
c -= AAA;
if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
if(c > i)
board[CASTLING][3] = c;
else
board[CASTLING][4] = c;
} else { /* white rights */
if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
if(board[0][i] == WhiteKing) break;
if(i == BOARD_RGHT) break;
board[CASTLING][2] = i;
c -= AAA - 'a' + 'A';
if(board[0][c] >= WhiteKing) break;
if(c > i)
board[CASTLING][0] = c;
else
board[CASTLING][1] = c;
}
}
}
for(i=0; i<nrCastlingRights; i++)
if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
if(gameInfo.variant == VariantSChess)
for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
if(fischer && shuffle) appData.fischerCastling = TRUE;
if (appData.debugMode) {
fprintf(debugFP, "FEN castling rights:");
for(i=0; i<nrCastlingRights; i++)
fprintf(debugFP, " %d", board[CASTLING][i]);
fprintf(debugFP, "\n");
}
while(*p==' ') p++;
}
if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
/* read e.p. field in games that know e.p. capture */
if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
if(*p=='-') {
p++; board[EP_STATUS] = EP_NONE;
} else {
char c = *p++ - AAA;
if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
if(*p >= '0' && *p <='9') p++;
board[EP_STATUS] = c;
}
}
if(sscanf(p, "%d", &i) == 1) {
FENrulePlies = i; /* 50-move ply counter */
/* (The move number is still ignored) */
}
return TRUE;
}
void
EditPositionPasteFEN (char *fen)
{
if (fen != NULL) {
Board initial_position;
if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
DisplayError(_("Bad FEN position in clipboard"), 0);
return ;
} else {
int savedBlackPlaysFirst = blackPlaysFirst;
EditPositionEvent();
blackPlaysFirst = savedBlackPlaysFirst;
CopyBoard(boards[0], initial_position);
initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
DisplayBothClocks();
DrawPosition(FALSE, boards[currentMove]);
}
}
}
static char cseq[12] = "\\ ";
Boolean
set_cont_sequence (char *new_seq)
{
int len;
Boolean ret;
// handle bad attempts to set the sequence
if (!new_seq)
return 0; // acceptable error - no debug
len = strlen(new_seq);
ret = (len > 0) && (len < sizeof(cseq));
if (ret)
safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
else if (appData.debugMode)
fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
return ret;
}
/*
reformat a source message so words don't cross the width boundary. internal
newlines are not removed. returns the wrapped size (no null character unless
included in source message). If dest is NULL, only calculate the size required
for the dest buffer. lp argument indicats line position upon entry, and it's
passed back upon exit.
*/
int
wrap (char *dest, char *src, int count, int width, int *lp)
{
int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
cseq_len = strlen(cseq);
old_line = line = *lp;
ansi = len = clen = 0;
for (i=0; i < count; i++)
{
if (src[i] == '\033')
ansi = 1;
// if we hit the width, back up
if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
{
// store i & len in case the word is too long
old_i = i, old_len = len;
// find the end of the last word
while (i && src[i] != ' ' && src[i] != '\n')
{
i--;
len--;
}
// word too long? restore i & len before splitting it
if ((old_i-i+clen) >= width)
{
i = old_i;
len = old_len;
}
// extra space?
if (i && src[i-1] == ' ')
len--;
if (src[i] != ' ' && src[i] != '\n')
{
i--;
if (len)
len--;
}
// now append the newline and continuation sequence
if (dest)
dest[len] = '\n';
len++;
if (dest)
strncpy(dest+len, cseq, cseq_len);
len += cseq_len;
line = cseq_len;
clen = cseq_len;
continue;
}
if (dest)
dest[len] = src[i];
len++;
if (!ansi)
line++;
if (src[i] == '\n')
line = 0;
if (src[i] == 'm')
ansi = 0;
}
if (dest && appData.debugMode)
{
fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
count, width, line, len, *lp);
show_bytes(debugFP, src, count);
fprintf(debugFP, "\ndest: ");
show_bytes(debugFP, dest, len);
fprintf(debugFP, "\n");
}
*lp = dest ? line : old_line;
return len;
}
// [HGM] vari: routines for shelving variations
Boolean modeRestore = FALSE;
void
PushInner (int firstMove, int lastMove)
{
int i, j, nrMoves = lastMove - firstMove;
// push current tail of game on stack
savedResult[storedGames] = gameInfo.result;
savedDetails[storedGames] = gameInfo.resultDetails;
gameInfo.resultDetails = NULL;
savedFirst[storedGames] = firstMove;
savedLast [storedGames] = lastMove;
savedFramePtr[storedGames] = framePtr;
framePtr -= nrMoves; // reserve space for the boards
for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
CopyBoard(boards[framePtr+i], boards[firstMove+i]);
for(j=0; j<MOVE_LEN; j++)
moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
for(j=0; j<2*MOVE_LEN; j++)
parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
pvInfoList[firstMove+i-1].depth = 0;
commentList[framePtr+i] = commentList[firstMove+i];
commentList[firstMove+i] = NULL;
}
storedGames++;
forwardMostMove = firstMove; // truncate game so we can start variation
}
void
PushTail (int firstMove, int lastMove)
{
if(appData.icsActive) { // only in local mode
forwardMostMove = currentMove; // mimic old ICS behavior
return;
}
if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
PushInner(firstMove, lastMove);
if(storedGames == 1) GreyRevert(FALSE);
if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
}
void
PopInner (Boolean annotate)
{
int i, j, nrMoves;
char buf[8000], moveBuf[20];
ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
nrMoves = savedLast[storedGames] - currentMove;
if(annotate) {
int cnt = 10;
if(!WhiteOnMove(currentMove))
snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
for(i=currentMove; i<forwardMostMove; i++) {
if(WhiteOnMove(i))
snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
strcat(buf, moveBuf);
if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
}
strcat(buf, ")");
}
for(i=1; i<=nrMoves; i++) { // copy last variation back
CopyBoard(boards[currentMove+i], boards[framePtr+i]);
for(j=0; j<MOVE_LEN; j++)
moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
for(j=0; j<2*MOVE_LEN; j++)
parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
if(commentList[currentMove+i]) free(commentList[currentMove+i]);
commentList[currentMove+i] = commentList[framePtr+i];
commentList[framePtr+i] = NULL;
}
if(annotate) AppendComment(currentMove+1, buf, FALSE);
framePtr = savedFramePtr[storedGames];
gameInfo.result = savedResult[storedGames];
if(gameInfo.resultDetails != NULL) {
free(gameInfo.resultDetails);
}
gameInfo.resultDetails = savedDetails[storedGames];
forwardMostMove = currentMove + nrMoves;
}
Boolean
PopTail (Boolean annotate)
{
if(appData.icsActive) return FALSE; // only in local mode
if(!storedGames) return FALSE; // sanity
CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
PopInner(annotate);
if(currentMove < forwardMostMove) ForwardEvent(); else
HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
return TRUE;
}
void
CleanupTail ()
{ // remove all shelved variations
int i;
for(i=0; i<storedGames; i++) {
if(savedDetails[i])
free(savedDetails[i]);
savedDetails[i] = NULL;
}
for(i=framePtr; i<MAX_MOVES; i++) {
if(commentList[i]) free(commentList[i]);
commentList[i] = NULL;
}
framePtr = MAX_MOVES-1;
storedGames = 0;
}
void
LoadVariation (int index, char *text)
{ // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
int level = 0, move;
if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
// first find outermost bracketing variation
while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
if(*p == '{') wait = '}'; else
if(*p == '[') wait = ']'; else
if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
}
if(*p == wait) wait = NULLCHAR; // closing ]} found
p++;
}
if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
end[1] = NULLCHAR; // clip off comment beyond variation
ToNrEvent(currentMove-1);
PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
// kludge: use ParsePV() to append variation to game
move = currentMove;
ParsePV(start, TRUE, TRUE);
forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
ClearPremoveHighlights();
CommentPopDown();
ToNrEvent(currentMove+1);
}
int transparency[2];
void
LoadTheme ()
{
#define BUF_SIZ (2*MSG_SIZ)
char *p, *q, buf[BUF_SIZ];
if(engineLine && engineLine[0]) { // a theme was selected from the listbox
snprintf(buf, BUF_SIZ, "-theme %s", engineLine);
ParseArgsFromString(buf);
ActivateTheme(TRUE); // also redo colors
return;
}
p = nickName;
if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
{
int len;
q = appData.themeNames;
snprintf(buf, BUF_SIZ, "\"%s\"", nickName);
if(appData.useBitmaps) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt true -lbtf \"%s\"",
Shorten(appData.liteBackTextureFile));
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dbtf \"%s\" -lbtm %d -dbtm %d",
Shorten(appData.darkBackTextureFile),
appData.liteBackTextureMode,
appData.darkBackTextureMode );
} else {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt false");
}
if(!appData.useBitmaps || transparency[0]) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -lsc %s", Col2Text(2) ); // lightSquareColor
}
if(!appData.useBitmaps || transparency[1]) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dsc %s", Col2Text(3) ); // darkSquareColor
}
if(appData.useBorder) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub true -border \"%s\"",
appData.border);
} else {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub false");
}
if(appData.useFont) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
appData.renderPiecesWithFont,
appData.fontToPieceTable,
Col2Text(9), // appData.fontBackColorWhite
Col2Text(10) ); // appData.fontForeColorBlack
} else {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf false");
if(appData.pieceDirectory[0]) {
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -pid \"%s\"", Shorten(appData.pieceDirectory));
if(appData.trueColors != 2) // 2 is a kludge to suppress this in WinBoard
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -trueColors %s", appData.trueColors ? "true" : "false");
}
if(!appData.pieceDirectory[0] || !appData.trueColors)
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -wpc %s -bpc %s",
Col2Text(0), // whitePieceColor
Col2Text(1) ); // blackPieceColor
}
snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -hsc %s -phc %s\n",
Col2Text(4), // highlightSquareColor
Col2Text(5) ); // premoveHighlightColor
appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
if(insert != q) insert[-1] = NULLCHAR;
snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
if(q) free(q);
}
ActivateTheme(FALSE);
}
|