summaryrefslogtreecommitdiff
path: root/apps/plugins/lua/fscanf.c
diff options
context:
space:
mode:
Diffstat (limited to 'apps/plugins/lua/fscanf.c')
0 files changed, 0 insertions, 0 deletions
id='n68' href='#n68'>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
/*
 * Implementation of 'Train Tracks', a puzzle from the Times on Saturday.
 *
 * "Lay tracks to enable the train to travel from village A to village B.
 * The numbers indicate how many sections of rail go in each row and
 * column. There are only straight rails and curved rails. The track
 * cannot cross itself."
 *
 * Puzzles:
 * #9     8x8:d9s5c6zgAa,1,4,1,4,4,3,S3,5,2,2,4,S5,3,3,5,1
 * #112   8x8:w6x5mAa,1,3,1,4,6,4,S4,3,3,4,5,2,4,2,S5,1
 * #113   8x8:gCx5xAf,1,S4,2,5,4,6,2,3,4,2,5,2,S4,4,5,1
 * #114   8x8:p5fAzkAb,1,6,3,3,3,S6,2,3,5,4,S3,3,5,1,5,1
 * #115   8x8:zi9d5tAb,1,3,4,5,3,S4,2,4,2,6,2,3,6,S3,3,1
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>

#include "puzzles.h"

/* --- Game parameters --- */

/*
 * Difficulty levels. I do some macro ickery here to ensure that my
 * enum and the various forms of my name list always match up.
 */
#define DIFFLIST(A) \
    A(EASY,Easy,e) \
    A(TRICKY,Tricky,t)

#define ENUM(upper,title,lower) DIFF_ ## upper,
#define TITLE(upper,title,lower) #title,
#define ENCODE(upper,title,lower) #lower
#define CONFIG(upper,title,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const tracks_diffnames[] = { DIFFLIST(TITLE) };
static char const tracks_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)

struct game_params {
    int w, h, diff;
    bool single_ones;
};

static game_params *default_params(void)
{
    game_params *ret = snew(game_params);

    ret->w = ret->h = 8;
    ret->diff = DIFF_TRICKY;
    ret->single_ones = true;

    return ret;
}

static const struct game_params tracks_presets[] = {
    {8, 8, DIFF_EASY, 1},
    {8, 8, DIFF_TRICKY, 1},
    {10, 8, DIFF_EASY, 1},
    {10, 8, DIFF_TRICKY, 1 },
    {10, 10, DIFF_EASY, 1},
    {10, 10, DIFF_TRICKY, 1},
    {15, 10, DIFF_EASY, 1},
    {15, 10, DIFF_TRICKY, 1},
    {15, 15, DIFF_EASY, 1},
    {15, 15, DIFF_TRICKY, 1},
};

static bool game_fetch_preset(int i, char **name, game_params **params)
{
    game_params *ret;
    char str[80];

    if (i < 0 || i >= lenof(tracks_presets))
        return false;

    ret = snew(game_params);
    *ret = tracks_presets[i];

    sprintf(str, "%dx%d %s", ret->w, ret->h, tracks_diffnames[ret->diff]);

    *name = dupstr(str);
    *params = ret;
    return true;
}

static void free_params(game_params *params)
{
    sfree(params);
}

static game_params *dup_params(const game_params *params)
{
    game_params *ret = snew(game_params);
    *ret = *params;		       /* structure copy */
    return ret;
}

static void decode_params(game_params *params, char const *string)
{
    params->w = params->h = atoi(string);
    while (*string && isdigit((unsigned char)*string)) string++;
    if (*string == 'x') {
        string++;
        params->h = atoi(string);
        while (*string && isdigit((unsigned char)*string)) string++;
    }
    if (*string == 'd') {
        int i;
        string++;
        params->diff = DIFF_TRICKY;
        for (i = 0; i < DIFFCOUNT; i++)
            if (*string == tracks_diffchars[i])
                params->diff = i;
        if (*string) string++;
    }
    params->single_ones = true;
    if (*string == 'o') {
        params->single_ones = false;
        string++;
    }

}

static char *encode_params(const game_params *params, bool full)
{
    char buf[120];

    sprintf(buf, "%dx%d", params->w, params->h);
    if (full)
        sprintf(buf + strlen(buf), "d%c%s",
                tracks_diffchars[params->diff],
                params->single_ones ? "" : "o");
    return dupstr(buf);
}

static config_item *game_configure(const game_params *params)
{
    config_item *ret;
    char buf[80];

    ret = snewn(5, config_item);

    ret[0].name = "Width";
    ret[0].type = C_STRING;
    sprintf(buf, "%d", params->w);
    ret[0].u.string.sval = dupstr(buf);

    ret[1].name = "Height";
    ret[1].type = C_STRING;
    sprintf(buf, "%d", params->h);
    ret[1].u.string.sval = dupstr(buf);

    ret[2].name = "Difficulty";
    ret[2].type = C_CHOICES;
    ret[2].u.choices.choicenames = DIFFCONFIG;
    ret[2].u.choices.selected = params->diff;

    ret[3].name = "Disallow consecutive 1 clues";
    ret[3].type = C_BOOLEAN;
    ret[3].u.boolean.bval = params->single_ones;

    ret[4].name = NULL;
    ret[4].type = C_END;

    return ret;
}

static game_params *custom_params(const config_item *cfg)
{
    game_params *ret = snew(game_params);

    ret->w = atoi(cfg[0].u.string.sval);
    ret->h = atoi(cfg[1].u.string.sval);
    ret->diff = cfg[2].u.choices.selected;
    ret->single_ones = cfg[3].u.boolean.bval;

    return ret;
}

static const char *validate_params(const game_params *params, bool full)
{
    /*
     * Generating anything under 4x4 runs into trouble of one kind
     * or another.
     */
    if (params->w < 4 || params->h < 4)
        return "Width and height must both be at least four";
    return NULL;
}

/* --- Game state --- */

/* flag usage copied from pearl */

#define R 1
#define U 2
#define L 4
#define D 8

#define MOVECHAR(m) ((m==R)?'R':(m==U)?'U':(m==L)?'L':(m==D)?'D':'?')

#define DX(d) ( ((d)==R) - ((d)==L) )
#define DY(d) ( ((d)==D) - ((d)==U) )

#define F(d) (((d << 2) | (d >> 2)) & 0xF)
#define C(d) (((d << 3) | (d >> 1)) & 0xF)
#define A(d) (((d << 1) | (d >> 3)) & 0xF)

#define LR (L | R)
#define RL (R | L)
#define UD (U | D)
#define DU (D | U)
#define LU (L | U)
#define UL (U | L)
#define LD (L | D)
#define DL (D | L)
#define RU (R | U)
#define UR (U | R)
#define RD (R | D)
#define DR (D | R)
#define ALLDIR 15
#define BLANK 0
#define UNKNOWN 15

static const int nbits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };

/* square grid flags */
#define S_TRACK 1     /* a track passes through this square (--> 2 edges) */
#define S_NOTRACK 2   /* no track passes through this square */
#define S_ERROR 4
#define S_CLUE 8
#define S_MARK 16

#define S_TRACK_SHIFT   16 /* U/D/L/R flags for edge track indicators */
#define S_NOTRACK_SHIFT 20 /* U/D/L/R flags for edge no-track indicators */

/* edge grid flags */
#define E_TRACK 1     /* a track passes through this edge */
#define E_NOTRACK 2   /* no track passes through this edge */

struct numbers {
    int refcount;
    int *numbers;     /* sz w+h */
    int row_s, col_s; /* stations: TODO think about multiple lines
                         (for bigger grids)? */
};

#define INGRID(state, gx, gy) ((gx) >= 0 && (gx) < (state)->p.w && \
                               (gy) >= 0 && (gy) < (state)->p.h)

struct game_state {
    game_params p;
    unsigned int *sflags;       /* size w*h */
    struct numbers *numbers;
    int *num_errors;            /* size w+h */
    bool completed, used_solve, impossible;
};

/* Return the four directions in which a particular edge flag is set, around a square. */
static int S_E_DIRS(const game_state *state, int sx, int sy,
                    unsigned int eflag) {
    return (state->sflags[sy*state->p.w+sx] >>
            ((eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT)) & ALLDIR;
}

/* Count the number of a particular edge flag around a grid square. */
static int S_E_COUNT(const game_state *state, int sx, int sy,
                     unsigned int eflag) {
    return nbits[S_E_DIRS(state, sx, sy, eflag)];
}

/* Return the two flags (E_TRACK and/or E_NOTRACK) set on a specific
 * edge of a square. */
static unsigned S_E_FLAGS(const game_state *state, int sx, int sy, int d) {
    unsigned f = state->sflags[sy*state->p.w+sx];
    int t = (f & (d << S_TRACK_SHIFT)), nt = (f & (d << S_NOTRACK_SHIFT));
    return (t ? E_TRACK : 0) | (nt ? E_NOTRACK : 0);
}

static bool S_E_ADJ(const game_state *state, int sx, int sy, int d, int *ax,
                    int *ay, unsigned int *ad) {
    if (d == L && sx > 0)            { *ax = sx-1; *ay = sy;   *ad = R; return true; }
    if (d == R && sx < state->p.w-1) { *ax = sx+1; *ay = sy;   *ad = L; return true; }
    if (d == U && sy > 0)            { *ax = sx;   *ay = sy-1; *ad = D; return true; }
    if (d == D && sy < state->p.h-1) { *ax = sx;   *ay = sy+1; *ad = U; return true; }

    return false;
}

/* Sets flag (E_TRACK or E_NOTRACK) on a given edge of a square. */
static void S_E_SET(game_state *state, int sx, int sy, int d,
                    unsigned int eflag) {
    unsigned shift = (eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT, ad;
    int ax, ay;

    state->sflags[sy*state->p.w+sx] |= (d << shift);

    if (S_E_ADJ(state, sx, sy, d, &ax, &ay, &ad)) {
        state->sflags[ay*state->p.w+ax] |= (ad << shift);
    }
}

/* Clears flag (E_TRACK or E_NOTRACK) on a given edge of a square. */
static void S_E_CLEAR(game_state *state, int sx, int sy, int d,
                      unsigned int eflag) {
    unsigned shift = (eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT, ad;
    int ax, ay;

    state->sflags[sy*state->p.w+sx] &= ~(d << shift);

    if (S_E_ADJ(state, sx, sy, d, &ax, &ay, &ad)) {
        state->sflags[ay*state->p.w+ax] &= ~(ad << shift);
    }
}

static void clear_game(game_state *state)
{
    int w = state->p.w, h = state->p.h;

    memset(state->sflags, 0, w*h * sizeof(unsigned int));

    memset(state->numbers->numbers, 0, (w+h) * sizeof(int));
    state->numbers->col_s = state->numbers->row_s = -1;

    memset(state->num_errors, 0, (w+h) * sizeof(int));

    state->completed = state->used_solve = state->impossible = false;
}

static game_state *blank_game(const game_params *params)
{
    game_state *state = snew(game_state);
    int w = params->w, h = params->h;

    state->p = *params;

    state->sflags = snewn(w*h, unsigned int);

    state->numbers = snew(struct numbers);
    state->numbers->refcount = 1;
    state->numbers->numbers = snewn(w+h, int);

    state->num_errors = snewn(w+h, int);

    clear_game(state);

    return state;
}

static void copy_game_flags(const game_state *src, game_state *dest)
{
    int w = src->p.w, h = src->p.h;

    memcpy(dest->sflags, src->sflags, w*h*sizeof(unsigned int));
}

static game_state *dup_game(const game_state *state)
{
    int w = state->p.w, h = state->p.h;
    game_state *ret = snew(game_state);

    ret->p = state->p;		       /* structure copy */

    ret->sflags = snewn(w*h, unsigned int);
    copy_game_flags(state, ret);

    ret->numbers = state->numbers;
    state->numbers->refcount++;
    ret->num_errors = snewn(w+h, int);
    memcpy(ret->num_errors, state->num_errors, (w+h)*sizeof(int));

    ret->completed = state->completed;
    ret->used_solve = state->used_solve;
    ret->impossible = state->impossible;

    return ret;
}

static void free_game(game_state *state)
{
    if (--state->numbers->refcount <= 0) {
        sfree(state->numbers->numbers);
        sfree(state->numbers);
    }
    sfree(state->num_errors);
    sfree(state->sflags);
    sfree(state);
}

#define NDIRS 4
static const unsigned int dirs_const[] = { U, D, L, R };

static unsigned int find_direction(game_state *state, random_state *rs,
                                   int x, int y)
{
    int i, nx, ny, w=state->p.w, h=state->p.h;
    unsigned int dirs[NDIRS];

    memcpy(dirs, dirs_const, sizeof(dirs));
    shuffle(dirs, NDIRS, sizeof(*dirs), rs);
    for (i = 0; i < NDIRS; i++) {
        nx = x + DX(dirs[i]);
        ny = y + DY(dirs[i]);
        if (nx >= 0 && nx < w && ny == h) {
            /* off the bottom of the board: we've finished the path. */
            return dirs[i];
        } else if (!INGRID(state, nx, ny)) {
            /* off the board: can't move here */
            continue;
        } else if (S_E_COUNT(state, nx, ny, E_TRACK) > 0) {
            /* already tracks here: can't move */
            continue;
        }
        return dirs[i];
    }
    return 0; /* no possible directions left. */
}

static bool check_completion(game_state *state, bool mark);

static void lay_path(game_state *state, random_state *rs)
{
    int px, py, w=state->p.w, h=state->p.h;
    unsigned int d;

start:
    clear_game(state);

    /* pick a random entry point, lay its left edge */
    state->numbers->row_s = py = random_upto(rs, h);
    px = 0;
    S_E_SET(state, px, py, L, E_TRACK);

    while (INGRID(state, px, py)) {
        d = find_direction(state, rs, px, py);
        if (d == 0)
            goto start; /* nowhere else to go, restart */

        S_E_SET(state, px, py, d, E_TRACK);
        px += DX(d);
        py += DY(d);
    }
    /* double-check we got to the right place */
    assert(px >= 0 && px < w && py == h);

    state->numbers->col_s = px;
}

static int tracks_solve(game_state *state, int diff, int *max_diff_out);
static void debug_state(game_state *state, const char *what);

/* Clue-setting algorithm:

 - first lay clues randomly until it's soluble
 - then remove clues randomly if removing them doesn't affect solubility

 - We start with two clues, one at each path entrance.

 More details:
 - start with an array of all square i positions
 - if the grid is already soluble by a level easier than we've requested,
    go back and make a new grid
 - if the grid is already soluble by our requested difficulty level, skip
    the clue-laying step
 - count the number of flags the solver managed to place, remember this.

 - to lay clues:
   - shuffle the i positions
   - for each possible clue position:
     - copy the solved board, strip it
     - take the next position, add a clue there on the copy
     - try and solve the copy
     - if it's soluble by a level easier than we've requested, continue (on
        to next clue position: putting a clue here makes it too easy)
     - if it's soluble by our difficulty level, we're done:
       - put the clue flag into the solved board
       - go to strip-clues.
     - if the solver didn't manage to place any more flags, continue (on to next
        clue position: putting a clue here didn't help he solver)
     - otherwise put the clue flag in the original board, and go on to the next
        clue position
   - if we get here and we've not solved it yet, we never will (did we really
      fill _all_ the clues in?!). Go back and make a new grid.

 - to strip clues:
   - shuffle the i positions
   - for each possible clue position:
     - if the solved grid doesn't have a clue here, skip
     - copy the solved board, remove this clue, strip it
     - try and solve the copy
     - assert that it is not soluble by a level easier than we've requested
       - (because this should never happen)
     - if this is (still) soluble by our difficulty level:
       - remove this clue from the solved board, it's redundant (with the other
          clues)

  - that should be it.
*/

static game_state *copy_and_strip(const game_state *state, game_state *ret, int flipcluei)
{
    int i, j, w = state->p.w, h = state->p.h;

    copy_game_flags(state, ret);

    /* Add/remove a clue before stripping, if required */

    if (flipcluei != -1)
        ret->sflags[flipcluei] ^= S_CLUE;

    /* All squares that are not clue squares have square track info erased, and some edge flags.. */

    for (i = 0; i < w*h; i++) {
        if (!(ret->sflags[i] & S_CLUE)) {
            ret->sflags[i] &= ~(S_TRACK|S_NOTRACK|S_ERROR|S_MARK);
            for (j = 0; j < 4; j++) {
                unsigned f = 1<<j;
                int xx = i%w + DX(f), yy = i/w + DY(f);
                if (!INGRID(state, xx, yy) || !(ret->sflags[yy*w+xx] & S_CLUE)) {
                    /* only erase an edge flag if neither side of the edge is S_CLUE. */
                    S_E_CLEAR(ret, i%w, i/w, f, E_TRACK);
                    S_E_CLEAR(ret, i%w, i/w, f, E_NOTRACK);
                }
            }
        }
    }
    return ret;
}

#ifdef STANDALONE_SOLVER
#include <stdarg.h>
static FILE *solver_diagnostics_fp = NULL;
static void solver_diagnostic(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(solver_diagnostics_fp, fmt, ap);
    va_end(ap);
    fputc('\n', solver_diagnostics_fp);
}
#define solverdebug(printf_params) do {         \
        if (solver_diagnostics_fp) {            \
            solver_diagnostic printf_params;    \
        }                                       \
    } while (0)
#else
#define solverdebug(printf_params) ((void)0)
#endif

static int solve_progress(const game_state *state) {
    int i, w = state->p.w, h = state->p.h, progress = 0;

    /* Work out how many flags the solver managed to set (either TRACK
       or NOTRACK) and return this as a progress measure, to check whether
       a partially-solved board gets any further than a previous partially-
       solved board. */

    for (i = 0; i < w*h; i++) {
        if (state->sflags[i] & S_TRACK) progress++;
        if (state->sflags[i] & S_NOTRACK) progress++;
        progress += S_E_COUNT(state, i%w, i/w, E_TRACK);
        progress += S_E_COUNT(state, i%w, i/w, E_NOTRACK);
    }
    return progress;
}

static bool check_phantom_moves(const game_state *state) {
    int x, y, i;

    /* Check that this state won't show 'phantom moves' at the start of the
     * game: squares which have multiple edge flags set but no clue flag
     * cause a piece of track to appear that isn't on a clue square. */

    for (x = 0; x < state->p.w; x++) {
        for (y = 0; y < state->p.h; y++) {
            i = y*state->p.w+x;
            if (state->sflags[i] & S_CLUE)
                continue;
            if (S_E_COUNT(state, x, y, E_TRACK) > 1)
                return true; /* found one! */
        }
    }
    return false;
}

static int add_clues(game_state *state, random_state *rs, int diff)
{
    int i, j, pi, w = state->p.w, h = state->p.h, progress, ret = 0, sr;
    int *positions = snewn(w*h, int), npositions = 0;
    int *nedges_previous_solve = snewn(w*h, int);
    game_state *scratch = dup_game(state);
    int diff_used;

    debug_state(state, "gen: Initial board");

    debug(("gen: Adding clues..."));

    /* set up the shuffly-position grid for later, used for adding clues:
     * we only bother adding clues where any edges are set. */
    for (i = 0; i < w*h; i++) {
        if (S_E_DIRS(state, i%w, i/w, E_TRACK) != 0) {
            positions[npositions++] = i;
        }
        nedges_previous_solve[i] = 0;
    }

    /* First, check whether the puzzle is already either too easy, or just right */
    scratch = copy_and_strip(state, scratch, -1);
    sr = tracks_solve(scratch, diff, &diff_used);
    if (diff_used < diff) {
        ret = -1; /* already too easy, even without adding clues. */
        debug(("gen:  ...already too easy, need new board."));
        goto done;
    }

    if (sr < 0)
        assert(!"Generator should not have created impossible puzzle");
    if (sr > 0) {
        ret = 1; /* already soluble without any extra clues. */
        debug(("gen:  ...soluble without clues, nothing to do."));
        goto done;
    }
    debug_state(scratch, "gen: Initial part-solved state: ");
    progress = solve_progress(scratch);
    debug(("gen: Initial solve progress is %d", progress));

    /* First, lay clues until we're soluble. */
    shuffle(positions, npositions, sizeof(int), rs);
    for (pi = 0; pi < npositions; pi++) {
        i = positions[pi]; /* pick a random position */
        if (state->sflags[i] & S_CLUE)
            continue; /* already a clue here (entrance location?) */
        if (nedges_previous_solve[i] == 2)
            continue; /* no point putting a clue here, we could solve both edges
                         with the previous set of clues */

        /* set a clue in that position (on a copy of the board) and test solubility */
        scratch = copy_and_strip(state, scratch, i);

        if (check_phantom_moves(scratch))
            continue; /* adding a clue here would add phantom track */

        if (tracks_solve(scratch, diff, &diff_used) > 0) {
            if (diff_used < diff) {
                continue; /* adding a clue here makes it too easy */
            }
            /* we're now soluble (and we weren't before): add this clue, and then
               start stripping clues */
            debug(("gen:  ...adding clue at (%d,%d), now soluble", i%w, i/w));
            state->sflags[i] |= S_CLUE;
            goto strip_clues;
        }
        if (solve_progress(scratch) > progress) {
            /* We've made more progress solving: add this clue, then. */
            progress = solve_progress(scratch);
            debug(("gen:  ... adding clue at (%d,%d), new progress %d", i%w, i/w, progress));
            state->sflags[i] |= S_CLUE;

            for (j = 0; j < w*h; j++)
                nedges_previous_solve[j] = S_E_COUNT(scratch, j%w, j/w, E_TRACK);
        }
    }
    /* If we got here we didn't ever manage to make the puzzle soluble
       (without making it too easily soluble, that is): give up. */

    debug(("gen: Unable to make soluble with clues, need new board."));
    ret = -1;
    goto done;

strip_clues:
    debug(("gen: Stripping clues."));

    /* Now, strip redundant clues (i.e. those without which the puzzle is still
       soluble) */
    shuffle(positions, npositions, sizeof(int), rs);
    for (pi = 0; pi < npositions; pi++) {
        i = positions[pi]; /* pick a random position */
        if (!(state->sflags[i] & S_CLUE))
            continue; /* no clue here to strip */
        if ((i%w == 0 && i/w == state->numbers->row_s) ||
                (i/w == (h-1) && i%w == state->numbers->col_s))
            continue; /* don't strip clues at entrance/exit */

        scratch = copy_and_strip(state, scratch, i);
        if (check_phantom_moves(scratch))
            continue; /* removing a clue here would add phantom track */

        if (tracks_solve(scratch, diff, NULL) > 0) {
            debug(("gen:  ... removing clue at (%d,%d), still soluble without it", i%w, i/w));
            state->sflags[i] &= ~S_CLUE; /* still soluble without this clue. */
        }
    }
    debug(("gen: Finished stripping clues."));
    ret = 1;

done:
    sfree(positions);
    free_game(scratch);
    return ret;
}

static char *new_game_desc(const game_params *params, random_state *rs,
                           char **aux, bool interactive)
{
    int i, j, w = params->w, h = params->h, x, y, ret;
    game_state *state;
    char *desc, *p;
    game_params adjusted_params;

    /*
     * 4x4 Tricky cannot be generated, so fall back to Easy.
     */
    if (w == 4 && h == 4 && params->diff > DIFF_EASY) {
        adjusted_params = *params;     /* structure copy */
        adjusted_params.diff = DIFF_EASY;
        params = &adjusted_params;
    }

    state = blank_game(params);

    /* --- lay the random path */

newpath:
    lay_path(state, rs);
    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            if (S_E_COUNT(state, x, y, E_TRACK) > 0) {
                state->sflags[y*w + x] |= S_TRACK;
            }
            if ((x == 0 && y == state->numbers->row_s) ||
                    (y == (h-1) && x == state->numbers->col_s)) {
                state->sflags[y*w + x] |= S_CLUE;
            }
        }
    }

    /* --- Update the clue numbers based on the tracks we have generated. */
    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            if (state->sflags[y*w + x] & S_TRACK) {
                state->numbers->numbers[x]++;
                state->numbers->numbers[y+w]++;
            }
        }
    }
    for (i = 0; i < w+h; i++) {
        if (state->numbers->numbers[i] == 0)
            goto newpath; /* too boring */
    }

    if (params->single_ones) {
        bool last_was_one = true, is_one; /* disallow 1 clue at entry point */
        for (i = 0; i < w+h; i++) {
            is_one = (state->numbers->numbers[i] == 1);
            if (is_one && last_was_one)
                goto newpath; /* disallow consecutive 1 clues. */
            last_was_one = is_one;
        }
        if (state->numbers->numbers[w+h-1] == 1)
            goto newpath; /* (disallow 1 clue at exit point) */
    }

    /* --- Add clues to make a soluble puzzle */
    ret = add_clues(state, rs, params->diff);
    if (ret != 1) goto newpath; /* couldn't make it soluble, or too easy */

    /* --- Generate the game desc based on the generated grid. */
    desc = snewn(w*h*3 + (w+h)*5, char);
    for (i = j = 0; i < w*h; i++) {
        if (!(state->sflags[i] & S_CLUE) && j > 0 &&
                desc[j-1] >= 'a' && desc[j-1] < 'z')
            desc[j-1]++;
        else if (!(state->sflags[i] & S_CLUE))
            desc[j++] = 'a';
        else {
            unsigned int f = S_E_DIRS(state, i%w, i/w, E_TRACK);
            desc[j++] = (f < 10) ? ('0' + f) : ('A' + (f-10));
        }
    }

    p = desc + j;
    for (x = 0; x < w; x++) {
        p += sprintf(p, ",%s%d", x == state->numbers->col_s ? "S" : "",
                     state->numbers->numbers[x]);
    }
    for (y = 0; y < h; y++) {
        p += sprintf(p, ",%s%d", y == state->numbers->row_s ? "S" : "",
                     state->numbers->numbers[y+w]);
    }
    *p++ = '\0';

    ret = tracks_solve(state, DIFFCOUNT, NULL);
    assert(ret >= 0);
    free_game(state);

    debug(("new_game_desc: %s", desc));
    return desc;
}

static const char *validate_desc(const game_params *params, const char *desc)
{
    int i = 0, w = params->w, h = params->h, in = 0, out = 0;

    while (*desc) {
        unsigned int f = 0;
        if (*desc >= '0' && *desc <= '9')
            f = (*desc - '0');
        else if (*desc >= 'A' && *desc <= 'F')
            f = (*desc - 'A' + 10);
        else if (*desc >= 'a' && *desc <= 'z')
            i += *desc - 'a';
        else
            return "Game description contained unexpected characters";

        if (f != 0) {
            if (nbits[f] != 2)
                return "Clue did not provide 2 direction flags";
        }
        i++;
        desc++;
        if (i == w*h) break;
    }
    for (i = 0; i < w+h; i++) {
        if (!*desc)
            return "Not enough numbers given after grid specification";
        else if (*desc != ',')
            return "Invalid character in number list";
        desc++;
        if (*desc == 'S') {
            if (i < w)
                out++;
            else
                in++;
            desc++;
        }
        while (*desc && isdigit((unsigned char)*desc)) desc++;
    }
    if (in != 1 || out != 1)
        return "Puzzle must have one entrance and one exit";
    if (*desc)
        return "Unexpected additional character at end of game description";
    return NULL;
}

static game_state *new_game(midend *me, const game_params *params, const char *desc)
{
    game_state *state = blank_game(params);
    int w = params->w, h = params->h, i = 0;

    while (*desc) {
        unsigned int f = 0;
        if (*desc >= '0' && *desc <= '9')
            f = (*desc - '0');
        else if (*desc >= 'A' && *desc <= 'F')
            f = (*desc - 'A' + 10);
        else if (*desc >= 'a' && *desc <= 'z')
            i += *desc - 'a';

        if (f != 0) {
            int x = i % w, y = i / w;
            assert(f < 16);
            assert(nbits[f] == 2);

            state->sflags[i] |= (S_TRACK | S_CLUE);
            if (f & U) S_E_SET(state, x, y, U, E_TRACK);
            if (f & D) S_E_SET(state, x, y, D, E_TRACK);
            if (f & L) S_E_SET(state, x, y, L, E_TRACK);
            if (f & R) S_E_SET(state, x, y, R, E_TRACK);
        }
        i++;
        desc++;
        if (i == w*h) break;
    }
    for (i = 0; i < w+h; i++) {
        assert(*desc == ',');
        desc++;

        if (*desc == 'S') {
            if (i < w)
                state->numbers->col_s = i;
            else
                state->numbers->row_s = i-w;
            desc++;
        }
        state->numbers->numbers[i] = atoi(desc);
        while (*desc && isdigit((unsigned char)*desc)) desc++;
    }

    assert(!*desc);

    return state;
}

static int solve_set_sflag(game_state *state, int x, int y,
                           unsigned int f, const char *why)
{
    int w = state->p.w, i = y*w + x;

    if (state->sflags[i] & f)
        return 0;
    solverdebug(("square (%d,%d) -> %s: %s",
           x, y, (f == S_TRACK ? "TRACK" : "NOTRACK"), why));
    if (state->sflags[i] & (f == S_TRACK ? S_NOTRACK : S_TRACK)) {
        solverdebug(("opposite flag already set there, marking IMPOSSIBLE"));
        state->impossible = true;
    }
    state->sflags[i] |= f;
    return 1;
}

static int solve_set_eflag(game_state *state, int x, int y, int d,
                           unsigned int f, const char *why)
{
    int sf = S_E_FLAGS(state, x, y, d);

    if (sf & f)
        return 0;
    solverdebug(("edge (%d,%d)/%c -> %s: %s", x, y,
           (d == U) ? 'U' : (d == D) ? 'D' : (d == L) ? 'L' : 'R',
           (f == S_TRACK ? "TRACK" : "NOTRACK"), why));
    if (sf & (f == E_TRACK ? E_NOTRACK : E_TRACK)) {
        solverdebug(("opposite flag already set there, marking IMPOSSIBLE"));
        state->impossible = true;
    }
    S_E_SET(state, x, y, d, f);
    return 1;
}

static int solve_update_flags(game_state *state)
{
    int x, y, i, w = state->p.w, h = state->p.h, did = 0;

    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            /* If a square is NOTRACK, all four edges must be. */
            if (state->sflags[y*w + x] & S_NOTRACK) {
                for (i = 0; i < 4; i++) {
                    unsigned int d = 1<<i;
                    did += solve_set_eflag(state, x, y, d, E_NOTRACK, "edges around NOTRACK");
                }
            }

            /* If 3 or more edges around a square are NOTRACK, the square is. */
            if (S_E_COUNT(state, x, y, E_NOTRACK) >= 3) {
                did += solve_set_sflag(state, x, y, S_NOTRACK, "square has >2 NOTRACK edges");
            }

            /* If any edge around a square is TRACK, the square is. */
            if (S_E_COUNT(state, x, y, E_TRACK) > 0) {
                did += solve_set_sflag(state, x, y, S_TRACK, "square has TRACK edge");
            }

            /* If a square is TRACK and 2 edges are NOTRACK,
               the other two edges must be TRACK. */
            if ((state->sflags[y*w + x] & S_TRACK) &&
                    (S_E_COUNT(state, x, y, E_NOTRACK) == 2) &&
                    (S_E_COUNT(state, x, y, E_TRACK) < 2)) {
                for (i = 0; i < 4; i++) {
                    unsigned int d = 1<<i;
                    if (!(S_E_FLAGS(state, x, y, d) & (E_TRACK|E_NOTRACK))) {
                        did += solve_set_eflag(state, x, y, d, E_TRACK,
                                               "TRACK square/2 NOTRACK edges");
                    }
                }
            }

            /* If a square is TRACK and 2 edges are TRACK, the other two
               must be NOTRACK. */
            if ((state->sflags[y*w + x] & S_TRACK) &&
                    (S_E_COUNT(state, x, y, E_TRACK) == 2) &&
                    (S_E_COUNT(state, x, y, E_NOTRACK) < 2)) {
                for (i = 0; i < 4; i++) {
                    unsigned int d = 1<<i;
                    if (!(S_E_FLAGS(state, x, y, d) & (E_TRACK|E_NOTRACK))) {
                        did += solve_set_eflag(state, x, y, d, E_NOTRACK,
                                               "TRACK square/2 TRACK edges");
                    }
                }
            }
        }
    }
    return did;
}

static int solve_count_col(game_state *state, int col, unsigned int f)
{
    int i, n, c = 0, h = state->p.h, w = state->p.w;
    for (n = 0, i = col; n < h; n++, i += w) {
        if (state->sflags[i] & f) c++;
    }
    return c;
}

static int solve_count_row(game_state *state, int row, unsigned int f)
{
    int i, n, c = 0, w = state->p.w;
    for (n = 0, i = w*row; n < state->p.w; n++, i++) {
        if (state->sflags[i] & f) c++;
    }
    return c;
}

static int solve_count_clues_sub(game_state *state, int si, int id, int n,
                                 int target, const char *what)
{
    int ctrack = 0, cnotrack = 0, did = 0, j, i, w = state->p.w;

    for (j = 0, i = si; j < n; j++, i += id) {
        if (state->sflags[i] & S_TRACK)
            ctrack++;
        if (state->sflags[i] & S_NOTRACK)
            cnotrack++;
    }
    if (ctrack == target) {
        /* everything that's not S_TRACK must be S_NOTRACK. */
        for (j = 0, i = si; j < n; j++, i += id) {
            if (!(state->sflags[i] & S_TRACK))
                did += solve_set_sflag(state, i%w, i/w, S_NOTRACK, what);
        }
    }
    if (cnotrack == (n-target)) {
        /* everything that's not S_NOTRACK must be S_TRACK. */
        for (j = 0, i = si; j < n; j++, i += id) {
            if (!(state->sflags[i] & S_NOTRACK))
                did += solve_set_sflag(state, i%w, i/w, S_TRACK, what);
        }
    }
    return did;
}

static int solve_count_clues(game_state *state)
{
    int w = state->p.w, h = state->p.h, x, y, target, did = 0;

    for (x = 0; x < w; x++) {
        target = state->numbers->numbers[x];
        did += solve_count_clues_sub(state, x, w, h, target, "col count");
    }
    for (y = 0; y < h; y++) {
        target = state->numbers->numbers[w+y];
        did += solve_count_clues_sub(state, y*w, 1, w, target, "row count");
    }
    return did;
}

static int solve_check_single_sub(game_state *state, int si, int id, int n,
                                  int target, unsigned int perpf,
                                  const char *what)
{
    int ctrack = 0, nperp = 0, did = 0, j, i, w = state->p.w;
    int n1edge = 0, i1edge = 0, ox, oy, x, y;
    unsigned int impossible = 0;

    /* For rows or columns which only have one more square to put a track in, we
       know the only way a new track section could be there would be to run
       perpendicular to the track (otherwise we'd need at least two free squares).
       So, if there is nowhere we can run perpendicular to the track (e.g. because
       we're on an edge) we know the extra track section much be on one end of an
       existing section. */

    for (j = 0, i = si; j < n; j++, i += id) {
        if (state->sflags[i] & S_TRACK)
            ctrack++;
        impossible = S_E_DIRS(state, i%w, i/w, E_NOTRACK);
        if ((perpf & impossible) == 0)
            nperp++;
        if (S_E_COUNT(state, i%w, i/w, E_TRACK) <= 1) {
            n1edge++;
            i1edge = i;
        }
    }
    if (ctrack != (target-1)) return 0;
    if (nperp > 0 || n1edge != 1) return 0;

    solverdebug(("check_single from (%d,%d): 1 match from (%d,%d)",
           si%w, si/w, i1edge%w, i1edge/w));

    /* We have a match: anything that's more than 1 away from this square
       cannot now contain a track. */
    ox = i1edge%w;
    oy = i1edge/w;
    for (j = 0, i = si; j < n; j++, i += id) {
        x = i%w;
        y = i/w;
        if (abs(ox-x) > 1 || abs(oy-y) > 1) {
            if (!(state->sflags[i] & S_TRACK))
                did += solve_set_sflag(state, x, y, S_NOTRACK, what);
        }
    }

    return did;
}

static int solve_check_single(game_state *state)
{
    int w = state->p.w, h = state->p.h, x, y, target, did = 0;

    for (x = 0; x < w; x++) {
        target = state->numbers->numbers[x];
        did += solve_check_single_sub(state, x, w, h, target, R|L, "single on col");
    }
    for (y = 0; y < h; y++) {
        target = state->numbers->numbers[w+y];
        did += solve_check_single_sub(state, y*w, 1, w, target, U|D, "single on row");
    }
    return did;
}

static int solve_check_loose_sub(game_state *state, int si, int id, int n,
                                 int target, unsigned int perpf,
                                 const char *what)
{
    int nperp = 0, nloose = 0, e2count = 0, did = 0, i, j, k;
    int w = state->p.w;
    unsigned int parf = ALLDIR & (~perpf);

    for (j = 0, i = si; j < n; j++, i += id) {
        int fcount = S_E_COUNT(state, i%w, i/w, E_TRACK);
        if (fcount == 2)
            e2count++; /* this cell has 2 definite edges */
        state->sflags[i] &= ~S_MARK;
        if (fcount == 1 && (parf & S_E_DIRS(state, i%w, i/w, E_TRACK))) {
            nloose++; /* this cell has a loose end (single flag set parallel
                    to the direction of this row/column) */
            state->sflags[i] |= S_MARK; /* mark loose ends */
        }
        if (fcount != 2 && !(perpf & S_E_DIRS(state, i%w, i/w, E_NOTRACK)))
            nperp++; /* we could lay perpendicular across this cell */
    }

    if (nloose > (target - e2count)) {
        solverdebug(("check %s from (%d,%d): more loose (%d) than empty (%d), IMPOSSIBLE",
               what, si%w, si/w, nloose, target-e2count));
        state->impossible = true;
    }
    if (nloose > 0 && nloose == (target - e2count)) {
        solverdebug(("check %s from (%d,%d): nloose = empty (%d), forcing loners out.",
               what, si%w, si/w, nloose));
        for (j = 0, i = si; j < n; j++, i += id) {
            if (!(state->sflags[i] & S_MARK))
                continue; /* skip non-loose ends */
            if (j > 0 && state->sflags[i-id] & S_MARK)
                continue; /* next to other loose end, could join up */
            if (j < (n-1) && state->sflags[i+id] & S_MARK)
                continue; /* ditto */

            for (k = 0; k < 4; k++) {
                if ((parf & (1<<k)) &&
                        !(S_E_DIRS(state, i%w, i/w, E_TRACK) & (1<<k))) {
                    /* set as NOTRACK the edge parallel to the row/column that's
                       not already set. */
                    did += solve_set_eflag(state, i%w, i/w, 1<<k, E_NOTRACK, what);
                }
            }
        }
    }
    if (nloose == 1 && (target - e2count) == 2 && nperp == 0) {
        solverdebug(("check %s from (%d,%d): 1 loose end, 2 empty squares, forcing parallel",
               what, si%w, si/w));
        for (j = 0, i = si; j < n; j++, i += id) {
            if (!(state->sflags[i] & S_MARK))
                continue; /* skip non-loose ends */
            for (k = 0; k < 4; k++) {
                if (parf & (1<<k))
                    did += solve_set_eflag(state, i%w, i/w, 1<<k, E_TRACK, what);
            }
        }
    }

    return did;
}

static int solve_check_loose_ends(game_state *state)
{
    int w = state->p.w, h = state->p.h, x, y, target, did = 0;

    for (x = 0; x < w; x++) {
        target = state->numbers->numbers[x];
        did += solve_check_loose_sub(state, x, w, h, target, R|L, "loose on col");
    }
    for (y = 0; y < h; y++) {
        target = state->numbers->numbers[w+y];
        did += solve_check_loose_sub(state, y*w, 1, w, target, U|D, "loose on row");
    }
    return did;
}

static int solve_check_loop_sub(game_state *state, int x, int y, int dir,
                                int *dsf, int startc, int endc)
{
    int w = state->p.w, h = state->p.h, i = y*w+x, j, k;
    bool satisfied = true;

    j = (y+DY(dir))*w + (x+DX(dir));

    assert(i < w*h && j < w*h);

    if ((state->sflags[i] & S_TRACK) &&
        (state->sflags[j] & S_TRACK) &&
        !(S_E_DIRS(state, x, y, E_TRACK) & dir) &&
        !(S_E_DIRS(state, x, y, E_NOTRACK) & dir)) {
        int ic = dsf_canonify(dsf, i), jc = dsf_canonify(dsf, j);
        if (ic == jc) {
            return solve_set_eflag(state, x, y, dir, E_NOTRACK, "would close loop");
        }
        if ((ic == startc && jc == endc) || (ic == endc && jc == startc)) {
            solverdebug(("Adding link at (%d,%d) would join start to end", x, y));
            /* We mustn't join the start to the end if:
               - there are other bits of track that aren't attached to either end
               - the clues are not fully satisfied yet
             */
            for (k = 0; k < w*h; k++) {
                if (state->sflags[k] & S_TRACK &&
                        dsf_canonify(dsf, k) != startc && dsf_canonify(dsf, k) != endc) {
                    return solve_set_eflag(state, x, y, dir, E_NOTRACK,
                                           "joins start to end but misses tracks");
                }
            }
            for (k = 0; k < w; k++) {
                int target = state->numbers->numbers[k];
                int ntracks = solve_count_col(state, k, S_TRACK);
                if (ntracks < target) satisfied = false;
            }
            for (k = 0; k < h; k++) {
                int target = state->numbers->numbers[w+k];
                int ntracks = solve_count_row(state, k, S_TRACK);
                if (ntracks < target) satisfied = false;
            }
            if (!satisfied) {
                return solve_set_eflag(state, x, y, dir, E_NOTRACK,
                                       "joins start to end with incomplete clues");
            }
        }
    }
    return 0;
}

static int solve_check_loop(game_state *state)
{
    int w = state->p.w, h = state->p.h, x, y, i, j, did = 0;
    int *dsf, startc, endc;

    /* TODO eventually we should pull this out into a solver struct and keep it
       updated as we connect squares. For now we recreate it every time we try
       this particular solver step. */
    dsf = snewn(w*h, int);
    dsf_init(dsf, w*h);

    /* Work out the connectedness of the current loop set. */
    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            i = y*w + x;
            if (x < (w-1) && S_E_DIRS(state, x, y, E_TRACK) & R) {
                /* connection to the right... */
                j = y*w + (x+1);
                assert(i < w*h && j < w*h);
                dsf_merge(dsf, i, j);
            }
            if (y < (h-1) && S_E_DIRS(state, x, y, E_TRACK) & D) {
                /* connection down... */
                j = (y+1)*w + x;
                assert(i < w*h && j < w*h);
                dsf_merge(dsf, i, j);
            }
            /* NB no need to check up and left because they'll have been checked
               by the other side. */
        }
    }

    startc = dsf_canonify(dsf, state->numbers->row_s*w);
    endc = dsf_canonify(dsf, (h-1)*w+state->numbers->col_s);

    /* Now look at all adjacent squares that are both S_TRACK: if connecting
       any of them would complete a loop (i.e. they're both the same dsf class
       already) then that edge must be NOTRACK. */
    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            if (x < (w-1))
              did += solve_check_loop_sub(state, x, y, R, dsf, startc, endc);
            if (y < (h-1))
              did += solve_check_loop_sub(state, x, y, D, dsf, startc, endc);
        }
    }

    sfree(dsf);

    return did;
}

static void solve_discount_edge(game_state *state, int x, int y, int d)
{
    if (S_E_DIRS(state, x, y, E_TRACK) & d) {
        assert(state->sflags[y*state->p.w + x] & S_CLUE);
        return; /* (only) clue squares can have outer edges set. */
    }
    solve_set_eflag(state, x, y, d, E_NOTRACK, "outer edge");
}

static int tracks_solve(game_state *state, int diff, int *max_diff_out)
{
    int x, y, w = state->p.w, h = state->p.h;
    int max_diff = DIFF_EASY;

    debug(("solve..."));
    state->impossible = false;

    /* Set all the outer border edges as no-track. */
    for (x = 0; x < w; x++) {
        solve_discount_edge(state, x, 0, U);
        solve_discount_edge(state, x, h-1, D);
    }
    for (y = 0; y < h; y++) {
        solve_discount_edge(state, 0, y, L);
        solve_discount_edge(state, w-1, y, R);
    }

    while (!state->impossible) {

/* Can't use do ... while (0) because we need a 'continue' in this macro */
#define TRY(curr_diff, funcall)                         \
        if (diff >= (curr_diff) && (funcall)) {         \
            if (max_diff < curr_diff)                   \
                max_diff = curr_diff;                   \
            continue;                                   \
        } else ((void)0)

        TRY(DIFF_EASY, solve_update_flags(state));
        TRY(DIFF_EASY, solve_count_clues(state));
        TRY(DIFF_EASY, solve_check_loop(state));

        TRY(DIFF_TRICKY, solve_check_single(state));
        TRY(DIFF_TRICKY, solve_check_loose_ends(state));


#undef TRY

        break;
    }

    sfree(sc->dsf);

    if (max_diff_out)
        *max_diff_out = max_diff;

    return state->impossible ? -1 : check_completion(state, false) ? 1 : 0;
}

static char *move_string_diff(const game_state *before, const game_state *after, bool issolve)
{
    int w = after->p.w, h = after->p.h, i, j;
    char *move = snewn(w*h*40, char), *p = move;
    const char *sep = "";
    unsigned int otf, ntf, onf, nnf;

    if (issolve) {
        *p++ = 'S';
        sep = ";";
    }
    for (i = 0; i < w*h; i++) {
        otf = S_E_DIRS(before, i%w, i/w, E_TRACK);
        ntf = S_E_DIRS(after, i%w, i/w, E_TRACK);
        onf = S_E_DIRS(before, i%w, i/w, E_NOTRACK);
        nnf = S_E_DIRS(after, i%w, i/w, E_NOTRACK);

        for (j = 0; j < 4; j++) {
            unsigned df = 1<<j;
            if ((otf & df) != (ntf & df)) {
                p += sprintf(p, "%s%c%c%d,%d", sep,
                             (ntf & df) ? 'T' : 't', MOVECHAR(df), i%w, i/w);
                sep = ";";
            }
            if ((onf & df) != (nnf & df)) {
                p += sprintf(p, "%s%c%c%d,%d", sep,
                             (nnf & df) ? 'N' : 'n', MOVECHAR(df), i%w, i/w);
                sep = ";";
            }
        }

        if ((before->sflags[i] & S_NOTRACK) != (after->sflags[i] & S_NOTRACK)) {
            p += sprintf(p, "%s%cS%d,%d", sep,
                         (after->sflags[i] & S_NOTRACK) ? 'N' : 'n', i%w, i/w);
            sep = ";";
        }
        if ((before->sflags[i] & S_TRACK) != (after->sflags[i] & S_TRACK)) {
            p += sprintf(p, "%s%cS%d,%d", sep,
                         (after->sflags[i] & S_TRACK) ? 'T' : 't', i%w, i/w);
            sep = ";";
        }
    }
    *p++ = '\0';
    move = sresize(move, p - move, char);

    return move;
}

static char *solve_game(const game_state *state, const game_state *currstate,
                        const char *aux, const char **error)
{
    game_state *solved;
    int ret;
    char *move;

    solved = dup_game(currstate);
    ret = tracks_solve(solved, DIFFCOUNT, NULL);
    if (ret < 1) {
        free_game(solved);
        solved = dup_game(state);
        ret = tracks_solve(solved, DIFFCOUNT, NULL);
    }

    if (ret < 1) {
        *error = "Unable to find solution";
        move = NULL;
    } else {
        move = move_string_diff(currstate, solved, true);
    }

    free_game(solved);
    return move;
}

static bool game_can_format_as_text_now(const game_params *params)
{
    return true;
}

static char *game_text_format(const game_state *state)
{
    char *ret, *p;
    int x, y, len, w = state->p.w, h = state->p.h;

    len = ((w*2) + 4) * ((h*2)+4) + 2;
    ret = snewn(len+1, char);
    p = ret;

    /* top line: column clues */
    *p++ = ' ';
    *p++ = ' ';
    for (x = 0; x < w; x++) {
        *p++ = (state->numbers->numbers[x] < 10 ?
                '0' + state->numbers->numbers[x] :
                'A' + state->numbers->numbers[x] - 10);
        *p++ = ' ';
    }
    *p++ = '\n';

    /* second line: top edge */
    *p++ = ' ';
    *p++ = '+';
    for (x = 0; x < w*2-1; x++)
        *p++ = '-';
    *p++ = '+';
    *p++ = '\n';

    /* grid rows: one line of squares, one line of edges. */
    for (y = 0; y < h; y++) {
        /* grid square line */
        *p++ = (y == state->numbers->row_s) ? 'A' : ' ';
        *p++ = (y == state->numbers->row_s) ? '-' : '|';

        for (x = 0; x < w; x++) {
            unsigned int f = S_E_DIRS(state, x, y, E_TRACK);
            if (state->sflags[y*w+x] & S_CLUE) *p++ = 'C';
            else if (f == LU || f == RD) *p++ = '/';
            else if (f == LD || f == RU) *p++ = '\\';
            else if (f == UD) *p++ = '|';
            else if (f == RL) *p++ = '-';
            else if (state->sflags[y*w+x] & S_NOTRACK) *p++ = 'x';
            else *p++ = ' ';

            if (x < w-1) {
                *p++ = (f & R) ? '-' : ' ';
            } else
                *p++ = '|';
        }
        *p++ = (state->numbers->numbers[w+y] < 10 ?
                '0' + state->numbers->numbers[w+y] :
                'A' + state->numbers->numbers[w+y] - 10);
        *p++ = '\n';

        if (y == h-1) continue;

        /* edges line */
        *p++ = ' ';
        *p++ = '|';
        for (x = 0; x < w; x++) {
            unsigned int f = S_E_DIRS(state, x, y, E_TRACK);
            *p++ = (f & D) ? '|' : ' ';
            *p++ = (x < w-1) ? ' ' : '|';
        }
        *p++ = '\n';
    }

    /* next line: bottom edge */
    *p++ = ' ';
    *p++ = '+';
    for (x = 0; x < w*2-1; x++)
        *p++ = (x == state->numbers->col_s*2) ? '|' : '-';
    *p++ = '+';
    *p++ = '\n';

    /* final line: bottom clue */
    *p++ = ' ';
    *p++ = ' ';
    for (x = 0; x < w*2-1; x++)
        *p++ = (x == state->numbers->col_s*2) ? 'B' : ' ';
    *p++ = '\n';

    *p = '\0';
    return ret;
}

static void debug_state(game_state *state, const char *what) {
    char *sstring = game_text_format(state);
    debug(("%s: %s", what, sstring));
    sfree(sstring);
}

static void dsf_update_completion(game_state *state, int ax, int ay,
                                  char dir, int *dsf)
{
    int w = state->p.w, ai = ay*w+ax, bx, by, bi;

    if (!(S_E_DIRS(state, ax, ay, E_TRACK) & dir)) return;
    bx = ax + DX(dir);
    by = ay + DY(dir);

    if (!INGRID(state, bx, by)) return;
    bi = by*w+bx;

    dsf_merge(dsf, ai, bi);
}

struct tracks_neighbour_ctx {
    game_state *state;
    int i, n, neighbours[4];
};
static int tracks_neighbour(int vertex, void *vctx)
{
    struct tracks_neighbour_ctx *ctx = (struct tracks_neighbour_ctx *)vctx;
    if (vertex >= 0) {
        game_state *state = ctx->state;
        int w = state->p.w, x = vertex % w, y = vertex / w;
        int dirs = S_E_DIRS(state, x, y, E_TRACK);
        int j;

        ctx->i = ctx->n = 0;

        for (j = 0; j < 4; j++) {
            int dir = 1<<j;
            if (dirs & dir) {
                int nx = x + DX(dir), ny = y + DY(dir);
                if (INGRID(state, nx, ny))
                    ctx->neighbours[ctx->n++] = ny * w + nx;
            }
        }
    }

    if (ctx->i < ctx->n)
        return ctx->neighbours[ctx->i++];
    else
        return -1;
}

static bool check_completion(game_state *state, bool mark)
{
    int w = state->p.w, h = state->p.h, x, y, i, target;
    bool ret = true;
    int ntrack, nnotrack, ntrackcomplete;
    int *dsf, pathclass;
    struct findloopstate *fls;
    struct tracks_neighbour_ctx ctx;

    if (mark) {
        for (i = 0; i < w+h; i++) {
            state->num_errors[i] = 0;
        }
        for (i = 0; i < w*h; i++) {
            state->sflags[i] &= ~S_ERROR;
            if (S_E_COUNT(state, i%w, i/w, E_TRACK) > 0) {
                if (S_E_COUNT(state, i%w, i/w, E_TRACK) > 2) {
                    ret = false;
                    state->sflags[i] |= S_ERROR;
                }
            }
        }
    }

    /* A cell is 'complete', for the purposes of marking the game as
     * finished, if it has two edges marked as TRACK. But it only has
     * to have one edge marked as TRACK, or be filled in as trackful
     * without any specific edges known, to count towards checking
     * row/column clue errors. */
    for (x = 0; x < w; x++) {
        target = state->numbers->numbers[x];
        ntrack = nnotrack = ntrackcomplete = 0;
        for (y = 0; y < h; y++) {
            if (S_E_COUNT(state, x, y, E_TRACK) > 0 ||
                state->sflags[y*w+x] & S_TRACK)
                ntrack++;
            if (S_E_COUNT(state, x, y, E_TRACK) == 2)
                ntrackcomplete++;
            if (state->sflags[y*w+x] & S_NOTRACK)
                nnotrack++;
        }
        if (mark) {
            if (ntrack > target || nnotrack > (h-target)) {
                debug(("col %d error: target %d, track %d, notrack %d",
                       x, target, ntrack, nnotrack));
                state->num_errors[x] = 1;
                ret = false;
            }
        }
        if (ntrackcomplete != target)
            ret = false;
    }
    for (y = 0; y < h; y++) {
        target = state->numbers->numbers[w+y];
        ntrack = nnotrack = ntrackcomplete = 0;
        for (x = 0; x < w; x++) {
            if (S_E_COUNT(state, x, y, E_TRACK) > 0 ||
                state->sflags[y*w+x] & S_TRACK)
                ntrack++;
            if (S_E_COUNT(state, x, y, E_TRACK) == 2)
                ntrackcomplete++;
            if (state->sflags[y*w+x] & S_NOTRACK)
                nnotrack++;
        }
        if (mark) {
            if (ntrack > target || nnotrack > (w-target)) {
                debug(("row %d error: target %d, track %d, notrack %d",
                       y, target, ntrack, nnotrack));
                state->num_errors[w+y] = 1;
                ret = false;
            }
        }
        if (ntrackcomplete != target)
            ret = false;
    }

    dsf = snewn(w*h, int);
    dsf_init(dsf, w*h);

    for (x = 0; x < w; x++) {
        for (y = 0; y < h; y++) {
            dsf_update_completion(state, x, y, R, dsf);
            dsf_update_completion(state, x, y, D, dsf);
        }
    }

    fls = findloop_new_state(w*h);
    ctx.state = state;
    if (findloop_run(fls, w*h, tracks_neighbour, &ctx)) {
        debug(("loop detected, not complete"));
        ret = false; /* no loop allowed */
        if (mark) {
            for (x = 0; x < w; x++) {
                for (y = 0; y < h; y++) {
                    int u, v;

                    u = y*w + x;
                    for (v = tracks_neighbour(u, &ctx); v >= 0;
                         v = tracks_neighbour(-1, &ctx))
                        if (findloop_is_loop_edge(fls, u, v))
                            state->sflags[y*w+x] |= S_ERROR;
                }
            }
        }
    }
    findloop_free_state(fls);

    if (mark) {
        pathclass = dsf_canonify(dsf, state->numbers->row_s*w);
        if (pathclass == dsf_canonify(dsf, (h-1)*w + state->numbers->col_s)) {
            /* We have a continuous path between the entrance and the exit: any
               other path must be in error. */
            for (i = 0; i < w*h; i++) {
                if ((dsf_canonify(dsf, i) != pathclass) &&
                    ((state->sflags[i] & S_TRACK) ||
                     (S_E_COUNT(state, i%w, i/w, E_TRACK) > 0))) {
                    ret = false;
                    state->sflags[i] |= S_ERROR;
                }
            }
        } else {
            /* If we _don't_ have such a path, then certainly the game
             * can't be in a winning state. So even if we're not
             * highlighting any _errors_, we certainly shouldn't
             * return true. */
            ret = false;
        }
    }

    if (mark)
        state->completed = ret;
    sfree(dsf);
    return ret;
}

/* Code borrowed from Pearl. */

struct game_ui {
    bool dragging, clearing, notrack;
    int drag_sx, drag_sy, drag_ex, drag_ey; /* drag start and end grid coords */
    int clickx, clicky;    /* pixel position of initial click */

    int curx, cury;        /* grid position of keyboard cursor; uses half-size grid */
    bool cursor_active;     /* true iff cursor is shown */
};

static game_ui *new_ui(const game_state *state)
{
    game_ui *ui = snew(game_ui);

    ui->clearing = false;
    ui->notrack = false;
    ui->dragging = false;
    ui->drag_sx = ui->drag_sy = ui->drag_ex = ui->drag_ey = -1;
    ui->cursor_active = false;
    ui->curx = ui->cury = 1;

    return ui;
}

static void free_ui(game_ui *ui)
{
    sfree(ui);
}

static char *encode_ui(const game_ui *ui)
{
    return NULL;
}

static void decode_ui(game_ui *ui, const char *encoding)
{
}

static void game_changed_state(game_ui *ui, const game_state *oldstate,
                               const game_state *newstate)
{
}

#define PREFERRED_TILE_SIZE 30
#define HALFSZ (ds->sz6*3)
#define THIRDSZ (ds->sz6*2)
#define TILE_SIZE (ds->sz6*6)

#define BORDER (TILE_SIZE/8)
#define LINE_THICK (TILE_SIZE/16)
#define GRID_LINE_TL (ds->grid_line_tl)
#define GRID_LINE_BR (ds->grid_line_br)
#define GRID_LINE_ALL (ds->grid_line_all)

#define COORD(x) ( (x+1) * TILE_SIZE + BORDER )
#define CENTERED_COORD(x) ( COORD(x) + TILE_SIZE/2 )
#define FROMCOORD(x) ( ((x) < BORDER) ? -1 : ( ((x) - BORDER) / TILE_SIZE) - 1 )

#define DS_DSHIFT 4     /* R/U/L/D shift, for drag-in-progress flags */

#define DS_ERROR (1 << 8)
#define DS_CLUE (1 << 9)
#define DS_NOTRACK (1 << 10)
#define DS_FLASH (1 << 11)
#define DS_CURSOR (1 << 12) /* cursor in square (centre, or on edge) */
#define DS_TRACK (1 << 13)
#define DS_CLEARING (1 << 14)

#define DS_NSHIFT 16    /* R/U/L/D shift, for no-track edge flags */
#define DS_CSHIFT 20    /* R/U/L/D shift, for cursor-on-edge */

struct game_drawstate {
    int sz6, grid_line_all, grid_line_tl, grid_line_br;
    bool started;

    int w, h, sz;
    unsigned int *flags, *flags_drag;
    int *num_errors;
};

static void update_ui_drag(const game_state *state, game_ui *ui, int gx, int gy)
{
    int w = state->p.w, h = state->p.h;
    int dx = abs(ui->drag_sx - gx), dy = abs(ui->drag_sy - gy);

    if (dy == 0) {
        ui->drag_ex = gx < 0 ? 0 : gx >= w ? w-1 : gx;
        ui->drag_ey = ui->drag_sy;
        ui->dragging = true;
    } else if (dx == 0) {
        ui->drag_ex = ui->drag_sx;
        ui->drag_ey = gy < 0 ? 0 : gy >= h ? h-1 : gy;
        ui->dragging = true;
    } else {
        ui->drag_ex = ui->drag_sx;
        ui->drag_ey = ui->drag_sy;
        ui->dragging = false;
    }
}

static bool ui_can_flip_edge(const game_state *state, int x, int y, int dir,
                             bool notrack)
{
    int w = state->p.w /*, h = state->shared->h, sz = state->shared->sz */;
    int x2 = x + DX(dir);
    int y2 = y + DY(dir);
    unsigned int sf1, sf2, ef;

    if (!INGRID(state, x, y) || !INGRID(state, x2, y2))
        return false;

    sf1 = state->sflags[y*w + x];
    sf2 = state->sflags[y2*w + x2];
    if ( !notrack && ((sf1 & S_CLUE) || (sf2 & S_CLUE)) )
        return false;

    ef = S_E_FLAGS(state, x, y, dir);
    if (notrack) {
      /* if we're going to _set_ NOTRACK (i.e. the flag is currently unset),
         make sure the edge is not already set to TRACK. The adjacent squares
         could be set to TRACK, because we don't know which edges the general
         square setting refers to. */
      if (!(ef & E_NOTRACK) && (ef & E_TRACK))
          return false;
    } else {
      if (!(ef & E_TRACK)) {
          /* if we're going to _set_ TRACK, make sure neither adjacent square nor
             the edge itself is already set to NOTRACK. */
          if ((sf1 & S_NOTRACK) || (sf2 & S_NOTRACK) || (ef & E_NOTRACK))
              return false;
          /* if we're going to _set_ TRACK, make sure neither adjacent square has
             2 track flags already.  */
          if ((S_E_COUNT(state, x, y, E_TRACK) >= 2) ||
              (S_E_COUNT(state, x2, y2, E_TRACK) >= 2))
              return false;
          }
    }
    return true;
}

static bool ui_can_flip_square(const game_state *state, int x, int y, bool notrack)
{
    int w = state->p.w, trackc;
    unsigned sf;

    if (!INGRID(state, x, y)) return false;
    sf = state->sflags[y*w+x];
    trackc = S_E_COUNT(state, x, y, E_TRACK);

    if (sf & S_CLUE) return false;

    if (notrack) {
        /* If we're setting S_NOTRACK, we cannot have either S_TRACK or any E_TRACK. */
        if (!(sf & S_NOTRACK) && ((sf & S_TRACK) || (trackc > 0)))
            return false;
    } else {
        /* If we're setting S_TRACK, we cannot have any S_NOTRACK (we could have
          E_NOTRACK, though, because one or two wouldn't rule out a track) */
        if (!(sf & S_TRACK) && (sf & S_NOTRACK))
            return false;
    }
    return true;
}

static char *edge_flip_str(const game_state *state, int x, int y, int dir, bool notrack, char *buf) {
    unsigned ef = S_E_FLAGS(state, x, y, dir);
    char c;

    if (notrack)
        c = (ef & E_NOTRACK) ? 'n' : 'N';
    else
        c = (ef & E_TRACK) ? 't' : 'T';

    sprintf(buf, "%c%c%d,%d", c, MOVECHAR(dir), x, y);
    return dupstr(buf);
}

static char *square_flip_str(const game_state *state, int x, int y, bool notrack, char *buf) {
    unsigned f = state->sflags[y*state->p.w+x];
    char c;

    if (notrack)
        c = (f & E_NOTRACK) ? 'n' : 'N';
    else
        c = (f & E_TRACK) ? 't' : 'T';

    sprintf(buf, "%cS%d,%d", c, x, y);
    return dupstr(buf);
}

#define SIGN(x) ((x<0) ? -1 : (x>0))

static game_state *copy_and_apply_drag(const game_state *state, const game_ui *ui)
{
    game_state *after = dup_game(state);
    int x1, y1, x2, y2, x, y, w = state->p.w;
    unsigned f = ui->notrack ? S_NOTRACK : S_TRACK, ff;

    x1 = min(ui->drag_sx, ui->drag_ex); x2 = max(ui->drag_sx, ui->drag_ex);
    y1 = min(ui->drag_sy, ui->drag_ey); y2 = max(ui->drag_sy, ui->drag_ey);

    /* actually either x1 == x2, or y1 == y2, but it's easier just to code
       the nested loop. */
    for (x = x1; x <= x2; x++) {
        for (y = y1; y <= y2; y++) {
            ff = state->sflags[y*w+x];
            if (ui->clearing && !(ff & f))
                continue; /* nothing to do, clearing and already clear */
            else if (!ui->clearing && (ff & f))
                continue; /* nothing to do, setting and already set */
            else if (ui_can_flip_square(state, x, y, ui->notrack))
                after->sflags[y*w+x] ^= f;
        }
    }
    return after;
}

#define KEY_DIRECTION(btn) (\
    (btn) == CURSOR_DOWN ? D : (btn) == CURSOR_UP ? U :\
    (btn) == CURSOR_LEFT ? L : R)

static char *interpret_move(const game_state *state, game_ui *ui,
                            const game_drawstate *ds,
                            int x, int y, int button)
{
    int w = state->p.w, h = state->p.h, direction;
    int gx = FROMCOORD(x), gy = FROMCOORD(y);
    char tmpbuf[80];

    /* --- mouse operations --- */

    if (IS_MOUSE_DOWN(button)) {
        ui->cursor_active = false;
        ui->dragging = false;

        if (!INGRID(state, gx, gy)) {
            /* can't drag from off grid */
            return NULL;
        }

        if (button == RIGHT_BUTTON) {
            ui->notrack = true;
            ui->clearing = state->sflags[gy*w+gx] & S_NOTRACK;
        } else {
            ui->notrack = false;
            ui->clearing = state->sflags[gy*w+gx] & S_TRACK;
        }

        ui->clickx = x;
        ui->clicky = y;
        ui->drag_sx = ui->drag_ex = gx;
        ui->drag_sy = ui->drag_ey = gy;

        return UI_UPDATE;
    }

    if (IS_MOUSE_DRAG(button)) {
        ui->cursor_active = false;
        update_ui_drag(state, ui, gx, gy);
        return UI_UPDATE;
    }

    if (IS_MOUSE_RELEASE(button)) {
        ui->cursor_active = false;
        if (ui->dragging &&
            (ui->drag_sx != ui->drag_ex || ui->drag_sy != ui->drag_ey)) {
            game_state *dragged = copy_and_apply_drag(state, ui);
            char *ret = move_string_diff(state, dragged, false);

            ui->dragging = false;
            free_game(dragged);

            return ret;
        } else {
            int cx, cy;

            /* We might still have been dragging (and just done a one-
             * square drag): cancel drag, so undo doesn't make it like
             * a drag-in-progress. */
            ui->dragging = false;

            /* Click (or tiny drag). Work out which edge we were
             * closest to. */

            /*
             * We process clicks based on the mouse-down location,
             * because that's more natural for a user to carefully
             * control than the mouse-up.
             */
            x = ui->clickx;
            y = ui->clicky;

            cx = CENTERED_COORD(gx);
            cy = CENTERED_COORD(gy);

            if (!INGRID(state, gx, gy) || FROMCOORD(x) != gx || FROMCOORD(y) != gy)
                return UI_UPDATE;

            if (max(abs(x-cx),abs(y-cy)) < TILE_SIZE/4) {
                if (ui_can_flip_square(state, gx, gy, button == RIGHT_RELEASE))
                    return square_flip_str(state, gx, gy, button == RIGHT_RELEASE, tmpbuf);
                return UI_UPDATE;
            } else {
                if (abs(x-cx) < abs(y-cy)) {
                    /* Closest to top/bottom edge. */
                    direction = (y < cy) ? U : D;
                } else {
                    /* Closest to left/right edge. */
                    direction = (x < cx) ? L : R;
                }
                if (ui_can_flip_edge(state, gx, gy, direction,
                        button == RIGHT_RELEASE))
                    return edge_flip_str(state, gx, gy, direction,
                            button == RIGHT_RELEASE, tmpbuf);
                else
                    return UI_UPDATE;
            }
        }
    }

    /* --- cursor/keyboard operations --- */

    if (IS_CURSOR_MOVE(button)) {
        int dx = (button == CURSOR_LEFT) ? -1 : ((button == CURSOR_RIGHT) ? +1 : 0);
        int dy = (button == CURSOR_DOWN) ? +1 : ((button == CURSOR_UP)    ? -1 : 0);

        if (!ui->cursor_active) {
            ui->cursor_active = true;
            return UI_UPDATE;
        }

        ui->curx = ui->curx + dx;
        ui->cury = ui->cury + dy;
        if ((ui->curx % 2 == 0) && (ui->cury % 2 == 0)) {
            /* disallow cursor on square corners: centres and edges only */
            ui->curx += dx; ui->cury += dy;
        }
        ui->curx = min(max(ui->curx, 1), 2*w-1);
        ui->cury = min(max(ui->cury, 1), 2*h-1);
        return UI_UPDATE;
    }

    if (IS_CURSOR_SELECT(button)) {
        if (!ui->cursor_active) {
            ui->cursor_active = true;
            return UI_UPDATE;
        }
        /* click on square corner does nothing (shouldn't get here) */
        if ((ui->curx % 2) == 0 && (ui->cury % 2 == 0))
            return UI_UPDATE;

        gx = ui->curx / 2;
        gy = ui->cury / 2;
        direction = ((ui->curx % 2) == 0) ? L : ((ui->cury % 2) == 0) ? U : 0;

        if (direction &&
            ui_can_flip_edge(state, gx, gy, direction, button == CURSOR_SELECT2))
            return edge_flip_str(state, gx, gy, direction, button == CURSOR_SELECT2, tmpbuf);
        else if (!direction &&
                 ui_can_flip_square(state, gx, gy, button == CURSOR_SELECT2))
            return square_flip_str(state, gx, gy, button == CURSOR_SELECT2, tmpbuf);
        return UI_UPDATE;
    }

#if 0
    /* helps to debug the solver */
    if (button == 'H' || button == 'h')
        return dupstr("H");
#endif

    return NULL;
}

static game_state *execute_move(const game_state *state, const char *move)
{
    int w = state->p.w, x, y, n, i;
    char c, d;
    unsigned f;
    game_state *ret = dup_game(state);

    /* this is breaking the bank on GTK, which vsprintf's into a fixed-size buffer
     * which is 4096 bytes long. vsnprintf needs a feature-test macro to use, faff. */
    /*debug(("move: %s\n", move));*/

    while (*move) {
        c = *move;
        if (c == 'S') {
            ret->used_solve = true;
            move++;
        } else if (c == 'T' || c == 't' || c == 'N' || c == 'n') {
            /* set track, clear track; set notrack, clear notrack */
            move++;
            if (sscanf(move, "%c%d,%d%n", &d, &x, &y, &n) != 3)
                goto badmove;
            if (!INGRID(state, x, y)) goto badmove;

            f = (c == 'T' || c == 't') ? S_TRACK : S_NOTRACK;

            if (d == 'S') {
                if (c == 'T' || c == 'N')
                    ret->sflags[y*w+x] |= f;
                else
                    ret->sflags[y*w+x] &= ~f;
            } else if (d == 'U' || d == 'D' || d == 'L' || d == 'R') {
                for (i = 0; i < 4; i++) {
                    unsigned df = 1<<i;

                    if (MOVECHAR(df) == d) {
                        if (c == 'T' || c == 'N')
                            S_E_SET(ret, x, y, df, f);
                        else
                            S_E_CLEAR(ret, x, y, df, f);
                    }
                }
            } else
                goto badmove;
            move += n;
        } else if (c == 'H') {
            tracks_solve(ret, DIFFCOUNT, NULL);
            move++;
        } else {
            goto badmove;
        }
        if (*move == ';')
            move++;
        else if (*move)
            goto badmove;
    }

    check_completion(ret, true);

    return ret;

    badmove:
    free_game(ret);
    return NULL;
}

/* ----------------------------------------------------------------------
 * Drawing routines.
 */

#define FLASH_TIME 0.5F

static void game_compute_size(const game_params *params, int tilesize,
                              int *x, int *y)
{
    /* Ick: fake up `ds->tilesize' for macro expansion purposes */
    struct {
        int sz6;
    } ads, *ds = &ads;
    ads.sz6 = tilesize/6;
    *x = (params->w+2) * TILE_SIZE + 2 * BORDER;
    *y = (params->h+2) * TILE_SIZE + 2 * BORDER;
}

static void game_set_size(drawing *dr, game_drawstate *ds,
                          const game_params *params, int tilesize)
{
    ds->sz6 = tilesize/6;
    ds->grid_line_all = max(LINE_THICK, 1);
    ds->grid_line_br = ds->grid_line_all / 2;
    ds->grid_line_tl = ds->grid_line_all - ds->grid_line_br;
}

enum {
    COL_BACKGROUND, COL_LOWLIGHT, COL_HIGHLIGHT,
    COL_TRACK_BACKGROUND = COL_LOWLIGHT,
    COL_GRID, COL_CLUE, COL_CURSOR,
    COL_TRACK, COL_TRACK_CLUE, COL_SLEEPER,
    COL_DRAGON, COL_DRAGOFF,
    COL_ERROR, COL_FLASH, COL_ERROR_BACKGROUND,
    NCOLOURS
};

static float *game_colours(frontend *fe, int *ncolours)
{
    float *ret = snewn(3 * NCOLOURS, float);
    int i;

    game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);

    for (i = 0; i < 3; i++) {
        ret[COL_TRACK_CLUE       * 3 + i] = 0.0F;
        ret[COL_TRACK            * 3 + i] = 0.5F;
        ret[COL_CLUE             * 3 + i] = 0.0F;
        ret[COL_GRID             * 3 + i] = 0.75F;
        ret[COL_CURSOR           * 3 + i] = 0.6F;
        ret[COL_ERROR_BACKGROUND * 3 + i] = 1.0F;
    }

    ret[COL_SLEEPER * 3 + 0] = 0.5F;
    ret[COL_SLEEPER * 3 + 1] = 0.4F;
    ret[COL_SLEEPER * 3 + 2] = 0.1F;

    ret[COL_ERROR * 3 + 0] = 1.0F;
    ret[COL_ERROR * 3 + 1] = 0.0F;
    ret[COL_ERROR * 3 + 2] = 0.0F;

    ret[COL_DRAGON * 3 + 0] = 0.0F;
    ret[COL_DRAGON * 3 + 1] = 0.0F;
    ret[COL_DRAGON * 3 + 2] = 1.0F;

    ret[COL_DRAGOFF * 3 + 0] = 0.8F;
    ret[COL_DRAGOFF * 3 + 1] = 0.8F;
    ret[COL_DRAGOFF * 3 + 2] = 1.0F;

    ret[COL_FLASH * 3 + 0] = 1.0F;
    ret[COL_FLASH * 3 + 1] = 1.0F;
    ret[COL_FLASH * 3 + 2] = 1.0F;

    *ncolours = NCOLOURS;
    return ret;
}

static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
    struct game_drawstate *ds = snew(struct game_drawstate);
    int i;

    ds->sz6 = 0;
    ds->started = false;

    ds->w = state->p.w;
    ds->h = state->p.h;
    ds->sz = ds->w*ds->h;
    ds->flags = snewn(ds->sz, unsigned int);
    ds->flags_drag = snewn(ds->sz, unsigned int);
    for (i = 0; i < ds->sz; i++)
        ds->flags[i] = ds->flags_drag[i] = 0;

    ds->num_errors = snewn(ds->w+ds->h, int);
    for (i = 0; i < ds->w+ds->h; i++)
        ds->num_errors[i] = 0;

    return ds;
}

static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
    sfree(ds->flags);
    sfree(ds->flags_drag);
    sfree(ds->num_errors);
    sfree(ds);
}

static void draw_circle_sleepers(drawing *dr, game_drawstate *ds,
                                 float cx, float cy, float r2, float thickness, int c)
{
    float qr6 = (float)PI/12, qr3 = (float)PI/6, th, x1, y1, x2, y2;
    float t6 = THIRDSZ/2.0F, r1 = t6;
    int i;

    for (i = 0; i < 12; i++) {
        th = qr6 + (i*qr3);
        x1 = r1*(float)cos(th);
        x2 = r2*(float)cos(th);
        y1 = r1*(float)sin(th);
        y2 = r2*(float)sin(th);
        draw_thick_line(dr, thickness, cx+x1, cy+y1, cx+x2, cy+y2, c);
    }
}

static void draw_thick_circle_outline(drawing *dr, float thickness,
                                      float cx, float cy, float r,
                                      int colour)
{
    float circ4 = 0.5F * (float)PI * r, ang, x1, y1, x2, y2;
    int i, nseg;

    nseg = (int)(circ4 / 4.0F)*4; /* ensure a quarter-circle has a whole #segs */
    ang = 2.0F*(float)PI / nseg;

    for (i = 0; i < nseg; i++) {
        float th = ang * i, th2 = ang * (i+1);
        x1 = cx + r*(float)cos(th);
        x2 = cx + r*(float)cos(th2);
        y1 = cy + r*(float)sin(th);
        y2 = cy + r*(float)sin(th2);
        debug(("circ outline: x=%.2f -> %.2f, thick=%.2f", x1, x2, thickness));
        draw_thick_line(dr, thickness, x1, y1, x2, y2, colour);
    }
}

static void draw_tracks_specific(drawing *dr, game_drawstate *ds,
                                 int x, int y, unsigned int flags,
                                 int ctrack, int csleeper)
{
    float ox = (float)COORD(x), oy = (float)COORD(y), cx, cy;
    float t1 = (float)TILE_SIZE, t3 = TILE_SIZE/3.0F, t6 = TILE_SIZE/6.0F;
    int d, i;
    float thick_track = TILE_SIZE/8.0F, thick_sleeper = TILE_SIZE/12.0F;

    if (flags == LR) {
        for (i = 1; i <= 7; i+=2) {
            cx = ox + TILE_SIZE/8.0F*i;
            draw_thick_line(dr, thick_sleeper,
                            cx, oy+t6, cx, oy+t6+2*t3, csleeper);
        }
        draw_thick_line(dr, thick_track, ox, oy + t3, ox + TILE_SIZE, oy + t3, ctrack);
        draw_thick_line(dr, thick_track, ox, oy + 2*t3, ox + TILE_SIZE, oy + 2*t3, ctrack);
        return;
    }
    if (flags == UD) {
        for (i = 1; i <= 7; i+=2) {
            cy = oy + TILE_SIZE/8.0F*i;
            draw_thick_line(dr, thick_sleeper,
                            ox+t6, cy, ox+t6+2*t3, cy, csleeper);
        }
        debug(("vert line: x=%.2f, thick=%.2f", ox + t3, thick_track));
        draw_thick_line(dr, thick_track, ox + t3, oy, ox + t3, oy + TILE_SIZE, ctrack);
        draw_thick_line(dr, thick_track, ox + 2*t3, oy, ox + 2*t3, oy + TILE_SIZE, ctrack);
        return;
    }
    if (flags == UL || flags == DL || flags == UR || flags == DR) {
        cx = (flags & L) ? ox : ox + TILE_SIZE;
        cy = (flags & U) ? oy : oy + TILE_SIZE;

        draw_circle_sleepers(dr, ds, cx, cy, (float)(5*t6), thick_sleeper, csleeper);

        draw_thick_circle_outline(dr, thick_track, (float)cx, (float)cy,
                                  2*t3, ctrack);
        draw_thick_circle_outline(dr, thick_track, (float)cx, (float)cy,
                                  t3, ctrack);

        return;
    }

    for (d = 1; d < 16; d *= 2) {
        float ox1 = 0, ox2 = 0, oy1 = 0, oy2 = 0;

        if (!(flags & d)) continue;

        for (i = 1; i <= 2; i++) {
            if (d == L) {
                ox1 = 0;
                ox2 = thick_track;
                oy1 = oy2 = i*t3;
            } else if (d == R) {
                ox1 = t1;
                ox2 = t1 - thick_track;
                oy1 = oy2 = i*t3;
            } else if (d == U) {
                ox1 = ox2 = i*t3;
                oy1 = 0;
                oy2 = thick_track;
            } else if (d == D) {
                ox1 = ox2 = i*t3;
                oy1 = t1;
                oy2 = t1 - thick_track;
            }
            draw_thick_line(dr, thick_track, ox+ox1, oy+oy1, ox+ox2, oy+oy2, ctrack);
        }
    }
}

static unsigned int best_bits(unsigned int flags, unsigned int flags_drag, int *col)
{
    int nb_orig = nbits[flags & ALLDIR], nb_drag = nbits[flags_drag & ALLDIR];

    if (nb_orig > nb_drag) {
        *col = COL_DRAGOFF;
        return flags & ALLDIR;
    } else if (nb_orig < nb_drag) {
        *col = COL_DRAGON;
        return flags_drag & ALLDIR;
    }
    return flags & ALLDIR; /* same number of bits: no special colour. */
}

static void draw_square(drawing *dr, game_drawstate *ds,
                        int x, int y, unsigned int flags, unsigned int flags_drag)
{
    int t2 = HALFSZ, t16 = HALFSZ/4, off;
    int ox = COORD(x), oy = COORD(y), cx = ox + t2, cy = oy + t2, d, c;
    int bg = (flags & DS_TRACK) ? COL_TRACK_BACKGROUND : COL_BACKGROUND;
    unsigned int flags_best;

    assert(dr);

    /* Clip to the grid square. */
    clip(dr, ox, oy, TILE_SIZE, TILE_SIZE);

    /* Clear the square so that it's got an appropriately-sized border
     * in COL_GRID and a central area in the right background colour. */
    best_bits((flags & DS_TRACK) == DS_TRACK,
              (flags_drag & DS_TRACK) == DS_TRACK, &bg);
    draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE, COL_GRID);
    draw_rect(dr, ox + GRID_LINE_TL, oy + GRID_LINE_TL,
              TILE_SIZE - GRID_LINE_ALL, TILE_SIZE - GRID_LINE_ALL, bg);

    /* More outlines for clue squares. */
    if (flags & DS_CURSOR) {
        int curx, cury, curw, curh;

        off = t16;
        curx = ox + off; cury = oy + off;
        curw = curh = TILE_SIZE - (2*off) + 1;

        if (flags & (U << DS_CSHIFT)) {
            cury = oy - off; curh = 2*off + 1;
        } else if (flags & (D << DS_CSHIFT)) {
            cury = oy + TILE_SIZE - off; curh = 2*off + 1;
        } else if (flags & (L << DS_CSHIFT)) {
            curx = ox - off; curw = 2*off + 1;
        } else if (flags & (R << DS_CSHIFT)) {
            curx = ox + TILE_SIZE - off; curw = 2*off + 1;
        }

        draw_rect_outline(dr, curx, cury, curw, curh, COL_GRID);
    }

    /* Draw tracks themselves */
    c = (flags & DS_ERROR) ? COL_ERROR :
      (flags & DS_FLASH) ? COL_FLASH :
      (flags & DS_CLUE) ? COL_TRACK_CLUE : COL_TRACK;
    flags_best = best_bits(flags, flags_drag, &c);
    draw_tracks_specific(dr, ds, x, y, flags_best, c, COL_SLEEPER);

    /* Draw no-track marks, if present, in square and on edges. */
    c = COL_TRACK;
    flags_best = best_bits((flags & DS_NOTRACK) == DS_NOTRACK,
                           (flags_drag & DS_NOTRACK) == DS_NOTRACK, &c);
    if (flags_best) {
        off = HALFSZ/2;
        draw_thick_line(dr, LINE_THICK, cx - off, cy - off, cx + off, cy + off, c);
        draw_thick_line(dr, LINE_THICK, cx - off, cy + off, cx + off, cy - off, c);
    }

    c = COL_TRACK;
    flags_best = best_bits(flags >> DS_NSHIFT, flags_drag >> DS_NSHIFT, &c);
    for (d = 1; d < 16; d *= 2) {
        off = t16;
        cx = ox + t2;
        cy = oy + t2;

        if (flags_best & d) {
            cx += (d == R) ? t2 : (d == L) ? -t2 : 0;
            cy += (d == D) ? t2 : (d == U) ? -t2 : 0;

            draw_thick_line(dr, LINE_THICK, cx - off, cy - off, cx + off, cy + off, c);
            draw_thick_line(dr, LINE_THICK, cx - off, cy + off, cx + off, cy - off, c);
        }
    }

    unclip(dr);
    draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
}

static void draw_clue(drawing *dr, game_drawstate *ds, int w, int clue, int i, int col, int bg)
{
    int cx, cy, tsz = TILE_SIZE/2;
    char buf[20];

    if (i < w) {
        cx = CENTERED_COORD(i);
        cy = CENTERED_COORD(-1);
    } else {
        cx = CENTERED_COORD(w);
        cy = CENTERED_COORD(i-w);
    }

    if (bg >= 0)
        draw_rect(dr, cx - tsz + GRID_LINE_TL, cy - tsz + GRID_LINE_TL,
                  TILE_SIZE - GRID_LINE_ALL, TILE_SIZE - GRID_LINE_ALL, bg);
    sprintf(buf, "%d", clue);
    draw_text(dr, cx, cy, FONT_VARIABLE, tsz, ALIGN_VCENTRE|ALIGN_HCENTRE,
              col, buf);
    draw_update(dr, cx - tsz + GRID_LINE_TL, cy - tsz + GRID_LINE_TL,
                TILE_SIZE - GRID_LINE_ALL, TILE_SIZE - GRID_LINE_ALL);
}

static void draw_loop_ends(drawing *dr, game_drawstate *ds,
                           const game_state *state, int c)
{
    int tsz = TILE_SIZE/2;

    draw_text(dr, CENTERED_COORD(-1), CENTERED_COORD(state->numbers->row_s),
              FONT_VARIABLE, tsz, ALIGN_VCENTRE|ALIGN_HCENTRE,
              c, "A");

    draw_text(dr, CENTERED_COORD(state->numbers->col_s), CENTERED_COORD(state->p.h),
              FONT_VARIABLE, tsz, ALIGN_VCENTRE|ALIGN_HCENTRE,
              c, "B");
}

static unsigned int s2d_flags(const game_state *state, int x, int y, const game_ui *ui)
{
    unsigned int f;
    int w = state->p.w;

    f = S_E_DIRS(state, x, y, E_TRACK);
    f |= (S_E_DIRS(state, x, y, E_NOTRACK) << DS_NSHIFT);

    if (state->sflags[y*w+x] & S_ERROR)
        f |= DS_ERROR;
    if (state->sflags[y*w+x] & S_CLUE)
        f |= DS_CLUE;
    if (state->sflags[y*w+x] & S_NOTRACK)
        f |= DS_NOTRACK;
    if ((state->sflags[y*w+x] & S_TRACK) || (S_E_COUNT(state, x, y, E_TRACK) > 0))
        f |= DS_TRACK;

    if (ui->cursor_active) {
        if (ui->curx >= x*2 && ui->curx <= (x+1)*2 &&
            ui->cury >= y*2 && ui->cury <= (y+1)*2) {
            f |= DS_CURSOR;
            if (ui->curx == x*2)        f |= (L << DS_CSHIFT);
            if (ui->curx == (x+1)*2)    f |= (R << DS_CSHIFT);
            if (ui->cury == y*2)        f |= (U << DS_CSHIFT);
            if (ui->cury == (y+1)*2)    f |= (D << DS_CSHIFT);
        }
    }

    return f;
}

static void game_redraw(drawing *dr, game_drawstate *ds, const game_state *oldstate,
                        const game_state *state, int dir, const game_ui *ui,