summaryrefslogtreecommitdiffstats
path: root/apps/plugins/puzzles/src/towers.c
blob: aee088fb54a6d18508818ef15ef407f3a64a9d38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
/*
 * towers.c: the puzzle also known as 'Skyscrapers'.
 *
 * Possible future work:
 *
 *  - Relax the upper bound on grid size at 9?
 *     + I'd need TOCHAR and FROMCHAR macros a bit like group's, to
 * 	 be used wherever this code has +'0' or -'0'
 *     + the pencil marks in the drawstate would need a separate
 * 	 word to live in
 *     + the clues outside the grid would have to cope with being
 * 	 multi-digit, meaning in particular that the text formatting
 * 	 would become more unpleasant
 *     + most importantly, though, the solver just isn't fast
 * 	 enough. Even at size 9 it can't really do the solver_hard
 * 	 factorial-time enumeration at a sensible rate. Easy puzzles
 * 	 higher than that would be possible, but more latin-squarey
 * 	 than skyscrapery, as it were.
 */

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

#include "puzzles.h"
#include "latin.h"

/*
 * 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,solver_easy,e) \
    A(HARD,Hard,solver_hard,h) \
    A(EXTREME,Extreme,NULL,x) \
    A(UNREASONABLE,Unreasonable,NULL,u)
#define ENUM(upper,title,func,lower) DIFF_ ## upper,
#define TITLE(upper,title,func,lower) #title,
#define ENCODE(upper,title,func,lower) #lower
#define CONFIG(upper,title,func,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const towers_diffnames[] = { DIFFLIST(TITLE) };
static char const towers_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)

enum {
    COL_BACKGROUND,
    COL_GRID,
    COL_USER,
    COL_HIGHLIGHT,
    COL_ERROR,
    COL_PENCIL,
    COL_DONE,
    NCOLOURS
};

struct game_params {
    int w, diff;
};

struct clues {
    int refcount;
    int w;
    /*
     * An array of 4w integers, of which:
     *  - the first w run across the top
     *  - the next w across the bottom
     *  - the third w down the left
     *  - the last w down the right.
     */
    int *clues;

    /*
     * An array of w*w digits.
     */
    digit *immutable;
};

/*
 * Macros to compute clue indices and coordinates.
 */
#define STARTSTEP(start, step, index, w) do { \
    if (index < w) \
	start = index, step = w; \
    else if (index < 2*w) \
	start = (w-1)*w+(index-w), step = -w; \
    else if (index < 3*w) \
	start = w*(index-2*w), step = 1; \
    else \
	start = w*(index-3*w)+(w-1), step = -1; \
} while (0)
#define CSTARTSTEP(start, step, index, w) \
    STARTSTEP(start, step, (((index)+2*w)%(4*w)), w)
#define CLUEPOS(x, y, index, w) do { \
    if (index < w) \
	x = index, y = -1; \
    else if (index < 2*w) \
	x = index-w, y = w; \
    else if (index < 3*w) \
	x = -1, y = index-2*w; \
    else \
	x = w, y = index-3*w; \
} while (0)

#ifdef STANDALONE_SOLVER
static const char *const cluepos[] = {
    "above column", "below column", "left of row", "right of row"
};
#endif

struct game_state {
    game_params par;
    struct clues *clues;
    bool *clues_done;
    digit *grid;
    int *pencil;		       /* bitmaps using bits 1<<1..1<<n */
    bool completed, cheated;
};

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

    ret->w = 5;
    ret->diff = DIFF_EASY;

    return ret;
}

static const struct game_params towers_presets[] = {
    {  4, DIFF_EASY         },
    {  5, DIFF_EASY         },
    {  5, DIFF_HARD         },
    {  6, DIFF_EASY         },
    {  6, DIFF_HARD         },
    {  6, DIFF_EXTREME      },
    {  6, DIFF_UNREASONABLE },
};

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

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

    ret = snew(game_params);
    *ret = towers_presets[i]; /* structure copy */

    sprintf(buf, "%dx%d %s", ret->w, ret->w, towers_diffnames[ret->diff]);

    *name = dupstr(buf);
    *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)
{
    char const *p = string;

    params->w = atoi(p);
    while (*p && isdigit((unsigned char)*p)) p++;

    if (*p == 'd') {
        int i;
        p++;
        params->diff = DIFFCOUNT+1; /* ...which is invalid */
        if (*p) {
            for (i = 0; i < DIFFCOUNT; i++) {
                if (*p == towers_diffchars[i])
                    params->diff = i;
            }
            p++;
        }
    }
}

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

    sprintf(ret, "%d", params->w);
    if (full)
        sprintf(ret + strlen(ret), "d%c", towers_diffchars[params->diff]);

    return dupstr(ret);
}

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

    ret = snewn(3, config_item);

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

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

    ret[2].name = NULL;
    ret[2].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->diff = cfg[1].u.choices.selected;

    return ret;
}

static const char *validate_params(const game_params *params, bool full)
{
    if (params->w < 3 || params->w > 9)
        return "Grid size must be between 3 and 9";
    if (params->diff >= DIFFCOUNT)
        return "Unknown difficulty rating";
    return NULL;
}

/* ----------------------------------------------------------------------
 * Solver.
 */

struct solver_ctx {
    int w, diff;
    bool started;
    int *clues;
    long *iscratch;
    int *dscratch;
};

static int solver_easy(struct latin_solver *solver, void *vctx)
{
    struct solver_ctx *ctx = (struct solver_ctx *)vctx;
    int w = ctx->w;
    int c, i, j, n, m, furthest;
    int start, step, cstart, cstep, clue, pos, cpos;
    int ret = 0;
#ifdef STANDALONE_SOLVER
    char prefix[256];
#endif

    if (!ctx->started) {
	ctx->started = true;
	/*
	 * One-off loop to help get started: when a pair of facing
	 * clues sum to w+1, it must mean that the row consists of
	 * two increasing sequences back to back, so we can
	 * immediately place the highest digit by knowing the
	 * lengths of those two sequences.
	 */
	for (c = 0; c < 3*w; c = (c == w-1 ? 2*w : c+1)) {
	    int c2 = c + w;

	    if (ctx->clues[c] && ctx->clues[c2] &&
		ctx->clues[c] + ctx->clues[c2] == w+1) {
		STARTSTEP(start, step, c, w);
		CSTARTSTEP(cstart, cstep, c, w);
		pos = start + (ctx->clues[c]-1)*step;
		cpos = cstart + (ctx->clues[c]-1)*cstep;
		if (solver->cube[cpos*w+w-1]) {
#ifdef STANDALONE_SOLVER
		    if (solver_show_working) {
			printf("%*sfacing clues on %s %d are maximal:\n",
			       solver_recurse_depth*4, "",
			       c>=2*w ? "row" : "column", c % w + 1);
			printf("%*s  placing %d at (%d,%d)\n",
			       solver_recurse_depth*4, "",
			       w, pos%w+1, pos/w+1);
		    }
#endif
		    latin_solver_place(solver, pos%w, pos/w, w);
		    ret = 1;
		} else {
		    ret = -1;
		}
	    }
	}

	if (ret)
	    return ret;
    }

    /*
     * Go over every clue doing reasonably simple heuristic
     * deductions.
     */
    for (c = 0; c < 4*w; c++) {
	clue = ctx->clues[c];
	if (!clue)
	    continue;
	STARTSTEP(start, step, c, w);
	CSTARTSTEP(cstart, cstep, c, w);

	/* Find the location of each number in the row. */
	for (i = 0; i < w; i++)
	    ctx->dscratch[i] = w;
	for (i = 0; i < w; i++)
	    if (solver->grid[start+i*step])
		ctx->dscratch[solver->grid[start+i*step]-1] = i;

	n = m = 0;
	furthest = w;
	for (i = w; i >= 1; i--) {
	    if (ctx->dscratch[i-1] == w) {
		break;
	    } else if (ctx->dscratch[i-1] < furthest) {
		furthest = ctx->dscratch[i-1];
		m = i;
		n++;
	    }
	}
	if (clue == n+1 && furthest > 1) {
#ifdef STANDALONE_SOLVER
	    if (solver_show_working)
		sprintf(prefix, "%*sclue %s %d is nearly filled:\n",
			solver_recurse_depth*4, "",
			cluepos[c/w], c%w+1);
	    else
		prefix[0] = '\0';	       /* placate optimiser */
#endif
	    /*
	     * We can already see an increasing sequence of the very
	     * highest numbers, of length one less than that
	     * specified in the clue. All of those numbers _must_ be
	     * part of the clue sequence, so the number right next
	     * to the clue must be the final one - i.e. it must be
	     * bigger than any of the numbers between it and m. This
	     * allows us to rule out small numbers in that square.
	     *
	     * (This is a generalisation of the obvious deduction
	     * that when you see a clue saying 1, it must be right
	     * next to the largest possible number; and similarly,
	     * when you see a clue saying 2 opposite that, it must
	     * be right next to the second-largest.)
	     */
	    j = furthest-1;  /* number of small numbers we can rule out */
	    for (i = 1; i <= w && j > 0; i++) {
		if (ctx->dscratch[i-1] < w && ctx->dscratch[i-1] >= furthest)
		    continue;	       /* skip this number, it's elsewhere */
		j--;
		if (solver->cube[cstart*w+i-1]) {
#ifdef STANDALONE_SOLVER
		    if (solver_show_working) {
			printf("%s%*s  ruling out %d at (%d,%d)\n",
			       prefix, solver_recurse_depth*4, "",
			       i, start%w+1, start/w+1);
			prefix[0] = '\0';
		    }
#endif
		    solver->cube[cstart*w+i-1] = 0;
		    ret = 1;
		}
	    }
	}

	if (ret)
	    return ret;

#ifdef STANDALONE_SOLVER
	    if (solver_show_working)
		sprintf(prefix, "%*slower bounds for clue %s %d:\n",
			solver_recurse_depth*4, "",
			cluepos[c/w], c%w+1);
	    else
		prefix[0] = '\0';	       /* placate optimiser */
#endif

	i = 0;
	for (n = w; n > 0; n--) {
	    /*
	     * The largest number cannot occur in the first (clue-1)
	     * squares of the row, or else there wouldn't be space
	     * for a sufficiently long increasing sequence which it
	     * terminated. The second-largest number (not counting
	     * any that are known to be on the far side of a larger
	     * number and hence excluded from this sequence) cannot
	     * occur in the first (clue-2) squares, similarly, and
	     * so on.
	     */

	    if (ctx->dscratch[n-1] < w) {
		for (m = n+1; m < w; m++)
		    if (ctx->dscratch[m] < ctx->dscratch[n-1])
			break;
		if (m < w)
		    continue;	       /* this number doesn't count */
	    }

	    for (j = 0; j < clue - i - 1; j++)
		if (solver->cube[(cstart + j*cstep)*w+n-1]) {
#ifdef STANDALONE_SOLVER
		    if (solver_show_working) {
			int pos = start+j*step;
			printf("%s%*s  ruling out %d at (%d,%d)\n",
			       prefix, solver_recurse_depth*4, "",
			       n, pos%w+1, pos/w+1);
			prefix[0] = '\0';
		    }
#endif
		    solver->cube[(cstart + j*cstep)*w+n-1] = 0;
		    ret = 1;
		}
	    i++;
	}
    }

    if (ret)
	return ret;

    return 0;
}

static int solver_hard(struct latin_solver *solver, void *vctx)
{
    struct solver_ctx *ctx = (struct solver_ctx *)vctx;
    int w = ctx->w;
    int c, i, j, n, best, clue, start, step, ret;
    long bitmap;
#ifdef STANDALONE_SOLVER
    char prefix[256];
#endif

    /*
     * Go over every clue analysing all possibilities.
     */
    for (c = 0; c < 4*w; c++) {
	clue = ctx->clues[c];
	if (!clue)
	    continue;
	CSTARTSTEP(start, step, c, w);

	for (i = 0; i < w; i++)
	    ctx->iscratch[i] = 0;

	/*
	 * Instead of a tedious physical recursion, I iterate in the
	 * scratch array through all possibilities. At any given
	 * moment, i indexes the element of the box that will next
	 * be incremented.
	 */
	i = 0;
	ctx->dscratch[i] = 0;
	best = n = 0;
	bitmap = 0;

	while (1) {
	    if (i < w) {
		/*
		 * Find the next valid value for cell i.
		 */
		int limit = (n == clue ? best : w);
		int pos = start + step * i;
		for (j = ctx->dscratch[i] + 1; j <= limit; j++) {
		    if (bitmap & (1L << j))
			continue;      /* used this one already */
		    if (!solver->cube[pos*w+j-1])
			continue;      /* ruled out already */

		    /* Found one. */
		    break;
		}

		if (j > limit) {
		    /* No valid values left; drop back. */
		    i--;
		    if (i < 0)
			break;	       /* overall iteration is finished */
		    bitmap &= ~(1L << ctx->dscratch[i]);
		    if (ctx->dscratch[i] == best) {
			n--;
			best = 0;
			for (j = 0; j < i; j++)
			    if (best < ctx->dscratch[j])
				best = ctx->dscratch[j];
		    }
		} else {
		    /* Got a valid value; store it and move on. */
		    bitmap |= 1L << j;
		    ctx->dscratch[i++] = j;
		    if (j > best) {
			best = j;
			n++;
		    }
		    ctx->dscratch[i] = 0;
		}
	    } else {
		if (n == clue) {
		    for (j = 0; j < w; j++)
			ctx->iscratch[j] |= 1L << ctx->dscratch[j];
		}
		i--;
		bitmap &= ~(1L << ctx->dscratch[i]);
		if (ctx->dscratch[i] == best) {
		    n--;
		    best = 0;
		    for (j = 0; j < i; j++)
			if (best < ctx->dscratch[j])
			    best = ctx->dscratch[j];
		}
	    }
	}

#ifdef STANDALONE_SOLVER
	if (solver_show_working)
	    sprintf(prefix, "%*sexhaustive analysis of clue %s %d:\n",
		    solver_recurse_depth*4, "",
		    cluepos[c/w], c%w+1);
	else
	    prefix[0] = '\0';	       /* placate optimiser */
#endif

	ret = 0;

	for (i = 0; i < w; i++) {
	    int pos = start + step * i;
	    for (j = 1; j <= w; j++) {
		if (solver->cube[pos*w+j-1] &&
		    !(ctx->iscratch[i] & (1L << j))) {
#ifdef STANDALONE_SOLVER
		    if (solver_show_working) {
			printf("%s%*s  ruling out %d at (%d,%d)\n",
			       prefix, solver_recurse_depth*4, "",
			       j, pos/w+1, pos%w+1);
			prefix[0] = '\0';
		    }
#endif
		    solver->cube[pos*w+j-1] = 0;
		    ret = 1;
		}
	    }

	    /*
	     * Once we find one clue we can do something with in
	     * this way, revert to trying easier deductions, so as
	     * not to generate solver diagnostics that make the
	     * problem look harder than it is.
	     */
	    if (ret)
		return ret;
	}
    }

    return 0;
}

#define SOLVER(upper,title,func,lower) func,
static usersolver_t const towers_solvers[] = { DIFFLIST(SOLVER) };

static bool towers_valid(struct latin_solver *solver, void *vctx)
{
    struct solver_ctx *ctx = (struct solver_ctx *)vctx;
    int w = ctx->w;
    int c, i, n, best, clue, start, step;
    for (c = 0; c < 4*w; c++) {
	clue = ctx->clues[c];
	if (!clue)
	    continue;

        STARTSTEP(start, step, c, w);
        n = best = 0;
        for (i = 0; i < w; i++) {
            if (solver->grid[start+i*step] > best) {
                best = solver->grid[start+i*step];
                n++;
            }
        }

        if (n != clue) {
#ifdef STANDALONE_SOLVER
            if (solver_show_working)
		printf("%*sclue %s %d is violated\n",
			solver_recurse_depth*4, "",
			cluepos[c/w], c%w+1);
#endif
            return false;
        }
    }
    return true;
}

static int solver(int w, int *clues, digit *soln, int maxdiff)
{
    int ret;
    struct solver_ctx ctx;

    ctx.w = w;
    ctx.diff = maxdiff;
    ctx.clues = clues;
    ctx.started = false;
    ctx.iscratch = snewn(w, long);
    ctx.dscratch = snewn(w+1, int);

    ret = latin_solver(soln, w, maxdiff,
		       DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
		       DIFF_EXTREME, DIFF_UNREASONABLE,
		       towers_solvers, towers_valid, &ctx, NULL, NULL);

    sfree(ctx.iscratch);
    sfree(ctx.dscratch);

    return ret;
}

/* ----------------------------------------------------------------------
 * Grid generation.
 */

static char *new_game_desc(const game_params *params, random_state *rs,
			   char **aux, bool interactive)
{
    int w = params->w, a = w*w;
    digit *grid, *soln, *soln2;
    int *clues, *order;
    int i, ret;
    int diff = params->diff;
    char *desc, *p;

    /*
     * Difficulty exceptions: some combinations of size and
     * difficulty cannot be satisfied, because all puzzles of at
     * most that difficulty are actually even easier.
     *
     * Remember to re-test this whenever a change is made to the
     * solver logic!
     *
     * I tested it using the following shell command:

for d in e h x u; do
  for i in {3..9}; do
    echo -n "./towers --generate 1 ${i}d${d}: "
    perl -e 'alarm 30; exec @ARGV' ./towers --generate 1 ${i}d${d} >/dev/null \
      && echo ok
  done
done

     * Of course, it's better to do that after taking the exceptions
     * _out_, so as to detect exceptions that should be removed as
     * well as those which should be added.
     */
    if (diff > DIFF_HARD && w <= 3)
	diff = DIFF_HARD;

    grid = NULL;
    clues = snewn(4*w, int);
    soln = snewn(a, digit);
    soln2 = snewn(a, digit);
    order = snewn(max(4*w,a), int);

    while (1) {
	/*
	 * Construct a latin square to be the solution.
	 */
	sfree(grid);
	grid = latin_generate(w, rs);

	/*
	 * Fill in the clues.
	 */
	for (i = 0; i < 4*w; i++) {
	    int start, step, j, k, best;
	    STARTSTEP(start, step, i, w);
	    k = best = 0;
	    for (j = 0; j < w; j++) {
		if (grid[start+j*step] > best) {
		    best = grid[start+j*step];
		    k++;
		}
	    }
	    clues[i] = k;
	}

	/*
	 * Remove the grid numbers and then the clues, one by one,
	 * for as long as the game remains soluble at the given
	 * difficulty.
	 */
	memcpy(soln, grid, a);

	if (diff == DIFF_EASY && w <= 5) {
	    /*
	     * Special case: for Easy-mode grids that are small
	     * enough, it's nice to be able to find completely empty
	     * grids.
	     */
	    memset(soln2, 0, a);
	    ret = solver(w, clues, soln2, diff);
	    if (ret > diff)
		continue;
	}

	for (i = 0; i < a; i++)
	    order[i] = i;
	shuffle(order, a, sizeof(*order), rs);
	for (i = 0; i < a; i++) {
	    int j = order[i];

	    memcpy(soln2, grid, a);
	    soln2[j] = 0;
	    ret = solver(w, clues, soln2, diff);
	    if (ret <= diff)
		grid[j] = 0;
	}

	if (diff > DIFF_EASY) {	       /* leave all clues on Easy mode */
	    for (i = 0; i < 4*w; i++)
		order[i] = i;
	    shuffle(order, 4*w, sizeof(*order), rs);
	    for (i = 0; i < 4*w; i++) {
		int j = order[i];
		int clue = clues[j];

		memcpy(soln2, grid, a);
		clues[j] = 0;
		ret = solver(w, clues, soln2, diff);
		if (ret > diff)
		    clues[j] = clue;
	    }
	}

	/*
	 * See if the game can be solved at the specified difficulty
	 * level, but not at the one below.
	 */
	memcpy(soln2, grid, a);
	ret = solver(w, clues, soln2, diff);
	if (ret != diff)
	    continue;		       /* go round again */

	/*
	 * We've got a usable puzzle!
	 */
	break;
    }

    /*
     * Encode the puzzle description.
     */
    desc = snewn(40*a, char);
    p = desc;
    for (i = 0; i < 4*w; i++) {
        if (i)
            *p++ = '/';
        if (clues[i])
            p += sprintf(p, "%d", clues[i]);
    }
    for (i = 0; i < a; i++)
	if (grid[i])
	    break;
    if (i < a) {
	int run = 0;

	*p++ = ',';

	for (i = 0; i <= a; i++) {
	    int n = (i < a ? grid[i] : -1);

	    if (!n)
		run++;
	    else {
		if (run) {
		    while (run > 0) {
			int thisrun = min(run, 26);
			*p++ = thisrun - 1 + 'a';
			run -= thisrun;
		    }
		} else {
		    /*
		     * If there's a number in the very top left or
		     * bottom right, there's no point putting an
		     * unnecessary _ before or after it.
		     */
		    if (i > 0 && n > 0)
			*p++ = '_';
		}
		if (n > 0)
		    p += sprintf(p, "%d", n);
		run = 0;
	    }
	}
    }
    *p++ = '\0';
    desc = sresize(desc, p - desc, char);

    /*
     * Encode the solution.
     */
    *aux = snewn(a+2, char);
    (*aux)[0] = 'S';
    for (i = 0; i < a; i++)
	(*aux)[i+1] = '0' + soln[i];
    (*aux)[a+1] = '\0';

    sfree(grid);
    sfree(clues);
    sfree(soln);
    sfree(soln2);
    sfree(order);

    return desc;
}

/* ----------------------------------------------------------------------
 * Gameplay.
 */

static const char *validate_desc(const game_params *params, const char *desc)
{
    int w = params->w, a = w*w;
    const char *p = desc;
    int i, clue;

    /*
     * Verify that the right number of clues are given, and that
     * they're in range.
     */
    for (i = 0; i < 4*w; i++) {
	if (!*p)
	    return "Too few clues for grid size";

	if (i > 0) {
	    if (*p != '/')
		return "Expected commas between clues";
	    p++;
	}

	if (isdigit((unsigned char)*p)) {
	    clue = atoi(p);
	    while (*p && isdigit((unsigned char)*p)) p++;

	    if (clue <= 0 || clue > w)
		return "Clue number out of range";
	}
    }
    if (*p == '/')
	return "Too many clues for grid size";

    if (*p == ',') {
	/*
	 * Verify that the right amount of grid data is given, and
	 * that any grid elements provided are in range.
	 */
	int squares = 0;

	p++;
	while (*p) {
	    int c = *p++;
	    if (c >= 'a' && c <= 'z') {
		squares += c - 'a' + 1;
	    } else if (c == '_') {
		/* do nothing */;
	    } else if (c > '0' && c <= '9') {
		int val = atoi(p-1);
		if (val < 1 || val > w)
		    return "Out-of-range number in grid description";
		squares++;
		while (*p && isdigit((unsigned char)*p)) p++;
	    } else
		return "Invalid character in game description";
	}

	if (squares < a)
	    return "Not enough data to fill grid";

	if (squares > a)
	    return "Too much data to fit in grid";
    }

    return NULL;
}

static key_label *game_request_keys(const game_params *params, int *nkeys)
{
    int i;
    int w = params->w;
    key_label *keys = snewn(w+1, key_label);
    *nkeys = w + 1;

    for (i = 0; i < w; i++) {
	if (i<9) keys[i].button = '1' + i;
	else keys[i].button = 'a' + i - 9;

        keys[i].label = NULL;
    }
    keys[w].button = '\b';
    keys[w].label = NULL;

    return keys;
}

static game_state *new_game(midend *me, const game_params *params,
                            const char *desc)
{
    int w = params->w, a = w*w;
    game_state *state = snew(game_state);
    const char *p = desc;
    int i;

    state->par = *params;	       /* structure copy */
    state->clues = snew(struct clues);
    state->clues->refcount = 1;
    state->clues->w = w;
    state->clues->clues = snewn(4*w, int);
    state->clues->immutable = snewn(a, digit);
    state->grid = snewn(a, digit);
    state->clues_done = snewn(4*w, bool);
    state->pencil = snewn(a, int);

    for (i = 0; i < a; i++) {
	state->grid[i] = 0;
	state->pencil[i] = 0;
    }

    memset(state->clues->immutable, 0, a);
    memset(state->clues_done, 0, 4*w*sizeof(bool));

    for (i = 0; i < 4*w; i++) {
	if (i > 0) {
	    assert(*p == '/');
	    p++;
	}
	if (*p && isdigit((unsigned char)*p)) {
	    state->clues->clues[i] = atoi(p);
	    while (*p && isdigit((unsigned char)*p)) p++;
	} else
	    state->clues->clues[i] = 0;
    }

    if (*p == ',') {
	int pos = 0;
	p++;
	while (*p) {
	    int c = *p++;
	    if (c >= 'a' && c <= 'z') {
		pos += c - 'a' + 1;
	    } else if (c == '_') {
		/* do nothing */;
	    } else if (c > '0' && c <= '9') {
		int val = atoi(p-1);
		assert(val >= 1 && val <= w);
		assert(pos < a);
		state->grid[pos] = state->clues->immutable[pos] = val;
		pos++;
		while (*p && isdigit((unsigned char)*p)) p++;
	    } else
		assert(!"Corrupt game description");
	}
	assert(pos == a);
    }
    assert(!*p);

    state->completed = false;
    state->cheated = false;

    return state;
}

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

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

    ret->clues = state->clues;
    ret->clues->refcount++;

    ret->grid = snewn(a, digit);
    ret->pencil = snewn(a, int);
    ret->clues_done = snewn(4*w, bool);
    memcpy(ret->grid, state->grid, a*sizeof(digit));
    memcpy(ret->pencil, state->pencil, a*sizeof(int));
    memcpy(ret->clues_done, state->clues_done, 4*w*sizeof(bool));

    ret->completed = state->completed;
    ret->cheated = state->cheated;

    return ret;
}

static void free_game(game_state *state)
{
    sfree(state->grid);
    sfree(state->pencil);
    sfree(state->clues_done);
    if (--state->clues->refcount <= 0) {
	sfree(state->clues->immutable);
	sfree(state->clues->clues);
	sfree(state->clues);
    }
    sfree(state);
}

static char *solve_game(const game_state *state, const game_state *currstate,
                        const char *aux, const char **error)
{
    int w = state->par.w, a = w*w;
    int i, ret;
    digit *soln;
    char *out;

    if (aux)
	return dupstr(aux);

    soln = snewn(a, digit);
    memcpy(soln, state->clues->immutable, a);

    ret = solver(w, state->clues->clues, soln, DIFFCOUNT-1);

    if (ret == diff_impossible) {
	*error = "No solution exists for this puzzle";
	out = NULL;
    } else if (ret == diff_ambiguous) {
	*error = "Multiple solutions exist for this puzzle";
	out = NULL;
    } else {
	out = snewn(a+2, char);
	out[0] = 'S';
	for (i = 0; i < a; i++)
	    out[i+1] = '0' + soln[i];
	out[a+1] = '\0';
    }

    sfree(soln);
    return out;
}

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

static char *game_text_format(const game_state *state)
{
    int w = state->par.w /* , a = w*w */;
    char *ret;
    char *p;
    int x, y;
    int total;

    /*
     * We have:
     * 	- a top clue row, consisting of three spaces, then w clue
     * 	  digits with spaces between (total 2*w+3 chars including
     * 	  newline)
     *  - a blank line (one newline)
     * 	- w main rows, consisting of a left clue digit, two spaces,
     * 	  w grid digits with spaces between, two spaces and a right
     * 	  clue digit (total 2*w+6 chars each including newline)
     *  - a blank line (one newline)
     *  - a bottom clue row (same as top clue row)
     *  - terminating NUL.
     *
     * Total size is therefore 2*(2*w+3) + 2 + w*(2*w+6) + 1
     * = 2w^2+10w+9.
     */
    total = 2*w*w + 10*w + 9;
    ret = snewn(total, char);
    p = ret;

    /* Top clue row. */
    *p++ = ' '; *p++ = ' ';
    for (x = 0; x < w; x++) {
	*p++ = ' ';
	*p++ = (state->clues->clues[x] ? '0' + state->clues->clues[x] : ' ');
    }
    *p++ = '\n';

    /* Blank line. */
    *p++ = '\n';

    /* Main grid. */
    for (y = 0; y < w; y++) {
	*p++ = (state->clues->clues[y+2*w] ? '0' + state->clues->clues[y+2*w] :
		' ');
	*p++ = ' ';
	for (x = 0; x < w; x++) {
	    *p++ = ' ';
	    *p++ = (state->grid[y*w+x] ? '0' + state->grid[y*w+x] : ' ');
	}
	*p++ = ' '; *p++ = ' ';
	*p++ = (state->clues->clues[y+3*w] ? '0' + state->clues->clues[y+3*w] :
		' ');
	*p++ = '\n';
    }

    /* Blank line. */
    *p++ = '\n';

    /* Bottom clue row. */
    *p++ = ' '; *p++ = ' ';
    for (x = 0; x < w; x++) {
	*p++ = ' ';
	*p++ = (state->clues->clues[x+w] ? '0' + state->clues->clues[x+w] :
		' ');
    }
    *p++ = '\n';

    *p++ = '\0';
    assert(p == ret + total);

    return ret;
}

struct game_ui {
    /*
     * These are the coordinates of the currently highlighted
     * square on the grid, if hshow = 1.
     */
    int hx, hy;
    /*
     * This indicates whether the current highlight is a
     * pencil-mark one or a real one.
     */
    bool hpencil;
    /*
     * This indicates whether or not we're showing the highlight
     * (used to be hx = hy = -1); important so that when we're
     * using the cursor keys it doesn't keep coming back at a
     * fixed position. When hshow = 1, pressing a valid number
     * or letter key or Space will enter that number or letter in the grid.
     */
    bool hshow;
    /*
     * This indicates whether we're using the highlight as a cursor;
     * it means that it doesn't vanish on a keypress, and that it is
     * allowed on immutable squares.
     */
    bool hcursor;
};

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

    ui->hx = ui->hy = 0;
    ui->hpencil = false;
    ui->hshow = false;
    ui->hcursor = false;

    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)
{
    int w = newstate->par.w;
    /*
     * We prevent pencil-mode highlighting of a filled square, unless
     * we're using the cursor keys. So if the user has just filled in
     * a square which we had a pencil-mode highlight in (by Undo, or
     * by Redo, or by Solve), then we cancel the highlight.
     */
    if (ui->hshow && ui->hpencil && !ui->hcursor &&
        newstate->grid[ui->hy * w + ui->hx] != 0) {
        ui->hshow = false;
    }
}

#define PREFERRED_TILESIZE 48
#define TILESIZE (ds->tilesize)
#define BORDER (TILESIZE * 9 / 8)
#define COORD(x) ((x)*TILESIZE + BORDER)
#define FROMCOORD(x) (((x)+(TILESIZE-BORDER)) / TILESIZE - 1)

/* These always return positive values, though y offsets are actually -ve */
#define X_3D_DISP(height, w) ((height) * TILESIZE / (8 * (w)))
#define Y_3D_DISP(height, w) ((height) * TILESIZE / (4 * (w)))

#define FLASH_TIME 0.4F

#define DF_PENCIL_SHIFT 16
#define DF_CLUE_DONE 0x10000
#define DF_ERROR 0x8000
#define DF_HIGHLIGHT 0x4000
#define DF_HIGHLIGHT_PENCIL 0x2000
#define DF_IMMUTABLE 0x1000
#define DF_PLAYAREA 0x0800
#define DF_DIGIT_MASK 0x00FF

struct game_drawstate {
    int tilesize;
    bool three_d;       /* default 3D graphics are user-disableable */
    bool started;
    long *tiles;		       /* (w+2)*(w+2) temp space */
    long *drawn;		       /* (w+2)*(w+2)*4: current drawn data */
    bool *errtmp;
};

static bool check_errors(const game_state *state, bool *errors)
{
    int w = state->par.w /*, a = w*w */;
    int W = w+2, A = W*W;	       /* the errors array is (w+2) square */
    int *clues = state->clues->clues;
    digit *grid = state->grid;
    int i, x, y;
    bool errs = false;
    int tmp[32];

    assert(w < lenof(tmp));

    if (errors)
	for (i = 0; i < A; i++)
	    errors[i] = false;

    for (y = 0; y < w; y++) {
	unsigned long mask = 0, errmask = 0;
	for (x = 0; x < w; x++) {
	    unsigned long bit = 1UL << grid[y*w+x];
	    errmask |= (mask & bit);
	    mask |= bit;
	}

	if (mask != (1L << (w+1)) - (1L << 1)) {
	    errs = true;
	    errmask &= ~1UL;
	    if (errors) {
		for (x = 0; x < w; x++)
		    if (errmask & (1UL << grid[y*w+x]))
			errors[(y+1)*W+(x+1)] = true;
	    }
	}
    }

    for (x = 0; x < w; x++) {
	unsigned long mask = 0, errmask = 0;
	for (y = 0; y < w; y++) {
	    unsigned long bit = 1UL << grid[y*w+x];
	    errmask |= (mask & bit);
	    mask |= bit;
	}

	if (mask != (1 << (w+1)) - (1 << 1)) {
	    errs = true;
	    errmask &= ~1UL;
	    if (errors) {
		for (y = 0; y < w; y++)
		    if (errmask & (1UL << grid[y*w+x]))
			errors[(y+1)*W+(x+1)] = true;
	    }
	}
    }

    for (i = 0; i < 4*w; i++) {
	int start, step, j, n, best;
	STARTSTEP(start, step, i, w);

	if (!clues[i])
	    continue;

	best = n = 0;
	for (j = 0; j < w; j++) {
	    int number = grid[start+j*step];
	    if (!number)
		break;		       /* can't tell what happens next */
	    if (number > best) {
		best = number;
		n++;
	    }
	}

	if (n > clues[i] || (best == w && n < clues[i]) ||
	    (best < w && n == clues[i])) {
	    if (errors) {
		int x, y;
		CLUEPOS(x, y, i, w);
		errors[(y+1)*W+(x+1)] = true;
	    }
	    errs = true;
	}
    }

    return errs;
}

static int clue_index(const game_state *state, int x, int y)
{
    int w = state->par.w;

    if (x == -1 || x == w)
        return w * (x == -1 ? 2 : 3) + y;
    else if (y == -1 || y == w)
        return (y == -1 ? 0 : w) + x;

    return -1;
}

static bool is_clue(const game_state *state, int x, int y)
{
    int w = state->par.w;

    if (((x == -1 || x == w) && y >= 0 && y < w) ||
        ((y == -1 || y == w) && x >= 0 && x < w))
    {
        if (state->clues->clues[clue_index(state, x, y)] & DF_DIGIT_MASK)
            return true;
    }

    return false;
}

static char *interpret_move(const game_state *state, game_ui *ui,
                            const game_drawstate *ds,
                            int x, int y, int button)
{
    int w = state->par.w;
    bool shift_or_control = button & (MOD_SHFT | MOD_CTRL);
    int tx, ty;
    char buf[80];

    button &= ~MOD_MASK;

    tx = FROMCOORD(x);
    ty = FROMCOORD(y);

    if (ds->three_d) {
	/*
	 * In 3D mode, just locating the mouse click in the natural
	 * square grid may not be sufficient to tell which tower the
	 * user clicked on. Investigate the _tops_ of the nearby
	 * towers to see if a click on one grid square was actually
	 * a click on a tower protruding into that region from
	 * another.
	 */
	int dx, dy;
	for (dy = 0; dy <= 1; dy++)
	    for (dx = 0; dx >= -1; dx--) {
		int cx = tx + dx, cy = ty + dy;
		if (cx >= 0 && cx < w && cy >= 0 && cy < w) {
		    int height = state->grid[cy*w+cx];
		    int bx = COORD(cx), by = COORD(cy);
		    int ox = bx + X_3D_DISP(height, w);
		    int oy = by - Y_3D_DISP(height, w);
		    if (/* on top face? */
			(x - ox >= 0 && x - ox < TILESIZE &&
			 y - oy >= 0 && y - oy < TILESIZE) ||
			/* in triangle between top-left corners? */
			(ox > bx && x >= bx && x <= ox && y <= by &&
			 (by-y) * (ox-bx) <= (by-oy) * (x-bx)) ||
			/* in triangle between bottom-right corners? */
			(ox > bx && x >= bx+TILESIZE && x <= ox+TILESIZE &&
			 y >= oy+TILESIZE &&
			 (by-y+TILESIZE)*(ox-bx) >= (by-oy)*(x-bx-TILESIZE))) {
			tx = cx;
			ty = cy;
		    }
		}
	    }
    }

    if (tx >= 0 && tx < w && ty >= 0 && ty < w) {
        if (button == LEFT_BUTTON) {
	    if (tx == ui->hx && ty == ui->hy &&
		ui->hshow && !ui->hpencil) {
                ui->hshow = false;
            } else {
                ui->hx = tx;
                ui->hy = ty;
		ui->hshow = !state->clues->immutable[ty*w+tx];
                ui->hpencil = false;
            }
            ui->hcursor = false;
            return UI_UPDATE;
        }
        if (button == RIGHT_BUTTON) {
            /*
             * Pencil-mode highlighting for non filled squares.
             */
            if (state->grid[ty*w+tx] == 0) {
                if (tx == ui->hx && ty == ui->hy &&
                    ui->hshow && ui->hpencil) {
                    ui->hshow = false;
                } else {
                    ui->hpencil = true;
                    ui->hx = tx;
                    ui->hy = ty;
                    ui->hshow = true;
                }
            } else {
                ui->hshow = false;
            }
            ui->hcursor = false;
            return UI_UPDATE;
        }
    } else if (button == LEFT_BUTTON) {
        if (is_clue(state, tx, ty)) {
            sprintf(buf, "%c%d,%d", 'D', tx, ty);
            return dupstr(buf);
        }
    }
    if (IS_CURSOR_MOVE(button)) {
        if (shift_or_control) {
            int x = ui->hx, y = ui->hy;
            switch (button) {
            case CURSOR_LEFT:   x = -1; break;
            case CURSOR_RIGHT:  x =  w; break;
            case CURSOR_UP:     y = -1; break;
            case CURSOR_DOWN:   y =  w; break;
            }
            if (is_clue(state, x, y)) {
                sprintf(buf, "%c%d,%d", 'D', x, y);
                return dupstr(buf);
            }
            return NULL;
        }
        move_cursor(button, &ui->hx, &ui->hy, w, w, false);
        ui->hshow = true;
        ui->hcursor = true;
        return UI_UPDATE;
    }
    if (ui->hshow &&
        (button == CURSOR_SELECT)) {
        ui->hpencil = !ui->hpencil;
        ui->hcursor = true;
        return UI_UPDATE;
    }

    if (ui->hshow &&
	((button >= '0' && button <= '9' && button - '0' <= w) ||
	 button == CURSOR_SELECT2 || button == '\b')) {
	int n = button - '0';
	if (button == CURSOR_SELECT2 || button == '\b')
	    n = 0;

        /*
         * Can't make pencil marks in a filled square. This can only
         * become highlighted if we're using cursor keys.
         */
        if (ui->hpencil && state->grid[ui->hy*w+ui->hx])
            return NULL;

	/*
	 * Can't do anything to an immutable square.
	 */
        if (state->clues->immutable[ui->hy*w+ui->hx])
            return NULL;

	sprintf(buf, "%c%d,%d,%d",
		(char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);

        if (!ui->hcursor) ui->hshow = false;

	return dupstr(buf);
    }

    if (button == 'M' || button == 'm')
        return dupstr("M");

    return NULL;
}

static game_state *execute_move(const game_state *from, const char *move)
{
    int w = from->par.w, a = w*w;
    game_state *ret = dup_game(from);
    int x, y, i, n;

    if (move[0] == 'S') {
	ret->completed = ret->cheated = true;

	for (i = 0; i < a; i++) {
            if (move[i+1] < '1' || move[i+1] > '0'+w)
                goto badmove;
	    ret->grid[i] = move[i+1] - '0';
	    ret->pencil[i] = 0;
	}

        if (move[a+1] != '\0')
            goto badmove;

	return ret;
    } else if ((move[0] == 'P' || move[0] == 'R') &&
	sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
	x >= 0 && x < w && y >= 0 && y < w && n >= 0 && n <= w) {
	if (from->clues->immutable[y*w+x])
            goto badmove;

        if (move[0] == 'P' && n > 0) {
            ret->pencil[y*w+x] ^= 1L << n;
        } else {
            ret->grid[y*w+x] = n;
            ret->pencil[y*w+x] = 0;

            if (!ret->completed && !check_errors(ret, NULL))
                ret->completed = true;
        }
	return ret;
    } else if (move[0] == 'M') {
	/*
	 * Fill in absolutely all pencil marks everywhere. (I
	 * wouldn't use this for actual play, but it's a handy
	 * starting point when following through a set of
	 * diagnostics output by the standalone solver.)
	 */
	for (i = 0; i < a; i++) {
	    if (!ret->grid[i])
		ret->pencil[i] = (1L << (w+1)) - (1L << 1);
	}
	return ret;
    } else if (move[0] == 'D' && sscanf(move+1, "%d,%d", &x, &y) == 2 &&
               is_clue(from, x, y)) {
        int index = clue_index(from, x, y);
        ret->clues_done[index] = !ret->clues_done[index];
        return ret;
    }

  badmove:
    /* couldn't parse move string */
    free_game(ret);
    return NULL;
}

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

#define SIZE(w) ((w) * TILESIZE + 2*BORDER)

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 tilesize; } ads, *ds = &ads;
    ads.tilesize = tilesize;

    *x = *y = SIZE(params->w);
}

static void game_set_size(drawing *dr, game_drawstate *ds,
                          const game_params *params, int tilesize)
{
    ds->tilesize = tilesize;
}

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

    frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);

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

    ret[COL_USER * 3 + 0] = 0.0F;
    ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
    ret[COL_USER * 3 + 2] = 0.0F;

    ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
    ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
    ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];

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

    ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
    ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
    ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];

    ret[COL_DONE * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] / 1.5F;
    ret[COL_DONE * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] / 1.5F;
    ret[COL_DONE * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] / 1.5F;

    *ncolours = NCOLOURS;
    return ret;
}

static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
{
    int w = state->par.w /*, a = w*w */;
    struct game_drawstate *ds = snew(struct game_drawstate);
    int i;

    ds->tilesize = 0;
    ds->three_d = !getenv("TOWERS_2D");
    ds->started = false;
    ds->tiles = snewn((w+2)*(w+2), long);
    ds->drawn = snewn((w+2)*(w+2)*4, long);
    for (i = 0; i < (w+2)*(w+2)*4; i++)
	ds->drawn[i] = -1;
    ds->errtmp = snewn((w+2)*(w+2), bool);

    return ds;
}

static void game_free_drawstate(drawing *dr, game_drawstate *ds)
{
    sfree(ds->errtmp);
    sfree(ds->tiles);
    sfree(ds->drawn);
    sfree(ds);
}

static void draw_tile(drawing *dr, game_drawstate *ds, struct clues *clues,
		      int x, int y, long tile)
{
    int w = clues->w /* , a = w*w */;
    int tx, ty, bg;
    char str[64];

    tx = COORD(x);
    ty = COORD(y);

    bg = (tile & DF_HIGHLIGHT) ? COL_HIGHLIGHT : COL_BACKGROUND;

    /* draw tower */
    if (ds->three_d && (tile & DF_PLAYAREA) && (tile & DF_DIGIT_MASK)) {
	int coords[8];
	int xoff = X_3D_DISP(tile & DF_DIGIT_MASK, w);
	int yoff = Y_3D_DISP(tile & DF_DIGIT_MASK, w);

	/* left face of tower */
	coords[0] = tx;
	coords[1] = ty - 1;
	coords[2] = tx;
	coords[3] = ty + TILESIZE - 1;
	coords[4] = coords[2] + xoff;
	coords[5] = coords[3] - yoff;
	coords[6] = coords[0] + xoff;
	coords[7] = coords[1] - yoff;
	draw_polygon(dr, coords, 4, bg, COL_GRID);

	/* bottom face of tower */
	coords[0] = tx + TILESIZE;
	coords[1] = ty + TILESIZE - 1;
	coords[2] = tx;
	coords[3] = ty + TILESIZE - 1;
	coords[4] = coords[2] + xoff;
	coords[5] = coords[3] - yoff;
	coords[6] = coords[0] + xoff;
	coords[7] = coords[1] - yoff;
	draw_polygon(dr, coords, 4, bg, COL_GRID);

	/* now offset all subsequent drawing to the top of the tower */
	tx += xoff;
	ty -= yoff;
    }

    /* erase background */
    draw_rect(dr, tx, ty, TILESIZE, TILESIZE, bg);

    /* pencil-mode highlight */
    if (tile & DF_HIGHLIGHT_PENCIL) {
        int coords[6];
        coords[0] = tx;
        coords[1] = ty;
        coords[2] = tx+TILESIZE/2;
        coords[3] = ty;
        coords[4] = tx;
        coords[5] = ty+TILESIZE/2;
        draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
    }

    /* draw box outline */
    if (tile & DF_PLAYAREA) {
        int coords[8];
        coords[0] = tx;
        coords[1] = ty - 1;
        coords[2] = tx + TILESIZE;
        coords[3] = ty - 1;
        coords[4] = tx + TILESIZE;
        coords[5] = ty + TILESIZE - 1;
        coords[6] = tx;
        coords[7] = ty + TILESIZE - 1;
        draw_polygon(dr, coords, 4, -1, COL_GRID);
    }

    /* new number needs drawing? */
    if (tile & DF_DIGIT_MASK) {
        int color;

	str[1] = '\0';
	str[0] = (tile & DF_DIGIT_MASK) + '0';

        if (tile & DF_ERROR)
            color = COL_ERROR;
        else if (tile & DF_CLUE_DONE)
            color = COL_DONE;
        else if (x < 0 || y < 0 || x >= w || y >= w)
            color = COL_GRID;
        else if (tile & DF_IMMUTABLE)
            color = COL_GRID;
        else
            color = COL_USER;

	draw_text(dr, tx + TILESIZE/2, ty + TILESIZE/2, FONT_VARIABLE,
		  (tile & DF_PLAYAREA ? TILESIZE/2 : TILESIZE*2/5),
                  ALIGN_VCENTRE | ALIGN_HCENTRE, color, str);
    } else {
        int i, j, npencil;
	int pl, pr, pt, pb;
	float bestsize;
	int pw, ph, minph, pbest, fontsize;

        /* Count the pencil marks required. */
        for (i = 1, npencil = 0; i <= w; i++)
            if (tile & (1L << (i + DF_PENCIL_SHIFT)))
		npencil++;
	if (npencil) {

	    minph = 2;

	    /*
	     * Determine the bounding rectangle within which we're going
	     * to put the pencil marks.
	     */
	    /* Start with the whole square, minus space for impinging towers */
	    pl = tx + (ds->three_d ? X_3D_DISP(w,w) : 0);
	    pr = tx + TILESIZE;
	    pt = ty;
	    pb = ty + TILESIZE - (ds->three_d ? Y_3D_DISP(w,w) : 0);

	    /*
	     * We arrange our pencil marks in a grid layout, with
	     * the number of rows and columns adjusted to allow the
	     * maximum font size.
	     *
	     * So now we work out what the grid size ought to be.
	     */
	    bestsize = 0.0;
	    pbest = 0;
	    /* Minimum */
	    for (pw = 3; pw < max(npencil,4); pw++) {
		float fw, fh, fs;

		ph = (npencil + pw - 1) / pw;
		ph = max(ph, minph);
		fw = (pr - pl) / (float)pw;
		fh = (pb - pt) / (float)ph;
		fs = min(fw, fh);
		if (fs > bestsize) {
		    bestsize = fs;
		    pbest = pw;
		}
	    }
	    assert(pbest > 0);
	    pw = pbest;
	    ph = (npencil + pw - 1) / pw;
	    ph = max(ph, minph);

	    /*
	     * Now we've got our grid dimensions, work out the pixel
	     * size of a grid element, and round it to the nearest
	     * pixel. (We don't want rounding errors to make the
	     * grid look uneven at low pixel sizes.)
	     */
	    fontsize = min((pr - pl) / pw, (pb - pt) / ph);

	    /*
	     * Centre the resulting figure in the square.
	     */
	    pl = pl + (pr - pl - fontsize * pw) / 2;
	    pt = pt + (pb - pt - fontsize * ph) / 2;

	    /*
	     * Now actually draw the pencil marks.
	     */
	    for (i = 1, j = 0; i <= w; i++)
		if (tile & (1L << (i + DF_PENCIL_SHIFT))) {
		    int dx = j % pw, dy = j / pw;

		    str[1] = '\0';
		    str[0] = i + '0';
		    draw_text(dr, pl + fontsize * (2*dx+1) / 2,
			      pt + fontsize * (2*dy+1) / 2,
			      FONT_VARIABLE, fontsize,
			      ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
		    j++;
		}
	}
    }
}

static void game_redraw(drawing *dr, game_drawstate *ds,
                        const game_state *oldstate, const game_state *state,
                        int dir, const game_ui *ui,
                        float animtime, float flashtime)
{
    int w = state->par.w /*, a = w*w */;
    int i, x, y;

    if (!ds->started) {
	/*
	 * The initial contents of the window are not guaranteed and
	 * can vary with front ends. To be on the safe side, all
	 * games should start by drawing a big background-colour
	 * rectangle covering the whole window.
	 */
	draw_rect(dr, 0, 0, SIZE(w), SIZE(w), COL_BACKGROUND);

	draw_update(dr, 0, 0, SIZE(w), SIZE(w));

	ds->started = true;
    }

    check_errors(state, ds->errtmp);

    /*
     * Work out what data each tile should contain.
     */
    for (i = 0; i < (w+2)*(w+2); i++)
	ds->tiles[i] = 0;	       /* completely blank square */
    /* The clue squares... */
    for (i = 0; i < 4*w; i++) {
	long tile = state->clues->clues[i];

	CLUEPOS(x, y, i, w);

	if (ds->errtmp[(y+1)*(w+2)+(x+1)])
	    tile |= DF_ERROR;
        else if (state->clues_done[i])
            tile |= DF_CLUE_DONE;

	ds->tiles[(y+1)*(w+2)+(x+1)] = tile;
    }
    /* ... and the main grid. */
    for (y = 0; y < w; y++) {
	for (x = 0; x < w; x++) {
	    long tile = DF_PLAYAREA;

	    if (state->grid[y*w+x])
		tile |= state->grid[y*w+x];
	    else
		tile |= (long)state->pencil[y*w+x] << DF_PENCIL_SHIFT;

	    if (ui->hshow && ui->hx == x && ui->hy == y)
		tile |= (ui->hpencil ? DF_HIGHLIGHT_PENCIL : DF_HIGHLIGHT);

	    if (state->clues->immutable[y*w+x])
		tile |= DF_IMMUTABLE;

            if (flashtime > 0 &&
                (flashtime <= FLASH_TIME/3 ||
                 flashtime >= FLASH_TIME*2/3))
                tile |= DF_HIGHLIGHT;  /* completion flash */

	    if (ds->errtmp[(y+1)*(w+2)+(x+1)])
		tile |= DF_ERROR;

	    ds->tiles[(y+1)*(w+2)+(x+1)] = tile;
	}
    }

    /*
     * Now actually draw anything that needs to be changed.
     */
    for (y = 0; y < w+2; y++) {
	for (x = 0; x < w+2; x++) {
	    long tl, tr, bl, br;
	    int i = y*(w+2)+x;

	    tr = ds->tiles[y*(w+2)+x];
	    tl = (x == 0 ? 0 : ds->tiles[y*(w+2)+(x-1)]);
	    br = (y == w+1 ? 0 : ds->tiles[(y+1)*(w+2)+x]);
	    bl = (x == 0 || y == w+1 ? 0 : ds->tiles[(y+1)*(w+2)+(x-1)]);

	    if (ds->drawn[i*4] != tl || ds->drawn[i*4+1] != tr ||
		ds->drawn[i*4+2] != bl || ds->drawn[i*4+3] != br) {
		clip(dr, COORD(x-1), COORD(y-1), TILESIZE, TILESIZE);

		draw_tile(dr, ds, state->clues, x-1, y-1, tr);
		if (x > 0)
		    draw_tile(dr, ds, state->clues, x-2, y-1, tl);
		if (y <= w)
		    draw_tile(dr, ds, state->clues, x-1, y, br);
		if (x > 0 && y <= w)
		    draw_tile(dr, ds, state->clues, x-2, y, bl);

		unclip(dr);
		draw_update(dr, COORD(x-1), COORD(y-1), TILESIZE, TILESIZE);

		ds->drawn[i*4] = tl;
		ds->drawn[i*4+1] = tr;
		ds->drawn[i*4+2] = bl;
		ds->drawn[i*4+3] = br;
	    }
	}
    }
}

static float game_anim_length(const game_state *oldstate,
                              const game_state *newstate, int dir, game_ui *ui)
{
    return 0.0F;
}

static float game_flash_length(const game_state *oldstate,
                               const game_state *newstate, int dir, game_ui *ui)
{
    if (!oldstate->completed && newstate->completed &&
	!oldstate->cheated && !newstate->cheated)
        return FLASH_TIME;
    return 0.0F;
}

static int game_status(const game_state *state)
{
    return state->completed ? +1 : 0;
}

static bool game_timing_state(const game_state *state, game_ui *ui)
{
    if (state->completed)
	return false;
    return true;
}

static void game_print_size(const game_params *params, float *x, float *y)
{
    int pw, ph;

    /*
     * We use 9mm squares by default, like Solo.
     */
    game_compute_size(params, 900, &pw, &ph);
    *x = pw / 100.0F;
    *y = ph / 100.0F;
}

static void game_print(drawing *dr, const game_state *state, int tilesize)
{
    int w = state->par.w;
    int ink = print_mono_colour(dr, 0);
    int i, x, y;

    /* Ick: fake up `ds->tilesize' for macro expansion purposes */
    game_drawstate ads, *ds = &ads;
    game_set_size(dr, ds, NULL, tilesize);

    /*
     * Border.
     */
    print_line_width(dr, 3 * TILESIZE / 40);
    draw_rect_outline(dr, BORDER, BORDER, w*TILESIZE, w*TILESIZE, ink);

    /*
     * Main grid.
     */
    for (x = 1; x < w; x++) {
	print_line_width(dr, TILESIZE / 40);
	draw_line(dr, BORDER+x*TILESIZE, BORDER,
		  BORDER+x*TILESIZE, BORDER+w*TILESIZE, ink);
    }
    for (y = 1; y < w; y++) {
	print_line_width(dr, TILESIZE / 40);
	draw_line(dr, BORDER, BORDER+y*TILESIZE,
		  BORDER+w*TILESIZE, BORDER+y*TILESIZE, ink);
    }

    /*
     * Clues.
     */
    for (i = 0; i < 4*w; i++) {
	char str[128];

	if (!state->clues->clues[i])
	    continue;

	CLUEPOS(x, y, i, w);

	sprintf (str, "%d", state->clues->clues[i]);

	draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
		  BORDER + y*TILESIZE + TILESIZE/2,
		  FONT_VARIABLE, TILESIZE/2,
		  ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
    }

    /*
     * Numbers for the solution, if any.
     */
    for (y = 0; y < w; y++)
	for (x = 0; x < w; x++)
	    if (state->grid[y*w+x]) {
		char str[2];
		str[1] = '\0';
		str[0] = state->grid[y*w+x] + '0';
		draw_text(dr, BORDER + x*TILESIZE + TILESIZE/2,
			  BORDER + y*TILESIZE + TILESIZE/2,
			  FONT_VARIABLE, TILESIZE/2,
			  ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
	    }
}

#ifdef COMBINED
#define thegame towers
#endif

const struct game thegame = {
    "Towers", "games.towers", "towers",
    default_params,
    game_fetch_preset, NULL,
    decode_params,
    encode_params,
    free_params,
    dup_params,
    true, game_configure, custom_params,
    validate_params,
    new_game_desc,
    validate_desc,
    new_game,
    dup_game,
    free_game,
    true, solve_game,
    true, game_can_format_as_text_now, game_text_format,
    new_ui,
    free_ui,
    encode_ui,
    decode_ui,
    game_request_keys,
    game_changed_state,
    interpret_move,
    execute_move,
    PREFERRED_TILESIZE, game_compute_size, game_set_size,
    game_colours,
    game_new_drawstate,
    game_free_drawstate,
    game_redraw,
    game_anim_length,
    game_flash_length,
    game_status,
    true, false, game_print_size, game_print,
    false,			       /* wants_statusbar */
    false, game_timing_state,
    REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
};

#ifdef STANDALONE_SOLVER

#include <stdarg.h>

int main(int argc, char **argv)
{
    game_params *p;
    game_state *s;
    char *id = NULL, *desc;
    const char *err;
    bool grade = false;
    int ret, diff;
    bool really_show_working = false;

    while (--argc > 0) {
        char *p = *++argv;
        if (!strcmp(p, "-v")) {
            really_show_working = true;
        } else if (!strcmp(p, "-g")) {
            grade = true;
        } else if (*p == '-') {
            fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
            return 1;
        } else {
            id = p;
        }
    }

    if (!id) {
        fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
        return 1;
    }

    desc = strchr(id, ':');
    if (!desc) {
        fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
        return 1;
    }
    *desc++ = '\0';

    p = default_params();
    decode_params(p, id);
    err = validate_desc(p, desc);
    if (err) {
        fprintf(stderr, "%s: %s\n", argv[0], err);
        return 1;
    }
    s = new_game(NULL, p, desc);

    /*
     * When solving an Easy puzzle, we don't want to bother the
     * user with Hard-level deductions. For this reason, we grade
     * the puzzle internally before doing anything else.
     */
    ret = -1;			       /* placate optimiser */
    solver_show_working = 0;
    for (diff = 0; diff < DIFFCOUNT; diff++) {
	memcpy(s->grid, s->clues->immutable, p->w * p->w);
	ret = solver(p->w, s->clues->clues, s->grid, diff);
	if (ret <= diff)
	    break;
    }

    if (really_show_working) {
        /*
         * Now run the solver again at the last difficulty level we
         * tried, but this time with diagnostics enabled.
         */
        solver_show_working = really_show_working;
        memcpy(s->grid, s->clues->immutable, p->w * p->w);
        ret = solver(p->w, s->clues->clues, s->grid,
                     diff < DIFFCOUNT ? diff : DIFFCOUNT-1);
    }

    if (diff == DIFFCOUNT) {
	if (grade)
	    printf("Difficulty rating: ambiguous\n");
	else
	    printf("Unable to find a unique solution\n");
    } else {
	if (grade) {
	    if (ret == diff_impossible)
		printf("Difficulty rating: impossible (no solution exists)\n");
	    else
		printf("Difficulty rating: %s\n", towers_diffnames[ret]);
	} else {
	    if (ret != diff)
		printf("Puzzle is inconsistent\n");
	    else
		fputs(game_text_format(s), stdout);
	}
    }

    return 0;
}

#endif

/* vim: set shiftwidth=4 tabstop=8: */