chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[sgt-puzzles.git] / solo.c
1 /*
2  * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3  *
4  * TODO:
5  *
6  *  - reports from users are that `Trivial'-mode puzzles are still
7  *    rather hard compared to newspapers' easy ones, so some better
8  *    low-end difficulty grading would be nice
9  *     + it's possible that really easy puzzles always have
10  *       _several_ things you can do, so don't make you hunt too
11  *       hard for the one deduction you can currently make
12  *     + it's also possible that easy puzzles require fewer
13  *       cross-eliminations: perhaps there's a higher incidence of
14  *       things you can deduce by looking only at (say) rows,
15  *       rather than things you have to check both rows and columns
16  *       for
17  *     + but really, what I need to do is find some really easy
18  *       puzzles and _play_ them, to see what's actually easy about
19  *       them
20  *     + while I'm revamping this area, filling in the _last_
21  *       number in a nearly-full row or column should certainly be
22  *       permitted even at the lowest difficulty level.
23  *     + also Owen noticed that `Basic' grids requiring numeric
24  *       elimination are actually very hard, so I wonder if a
25  *       difficulty gradation between that and positional-
26  *       elimination-only might be in order
27  *     + but it's not good to have _too_ many difficulty levels, or
28  *       it'll take too long to randomly generate a given level.
29  * 
30  *  - it might still be nice to do some prioritisation on the
31  *    removal of numbers from the grid
32  *     + one possibility is to try to minimise the maximum number
33  *       of filled squares in any block, which in particular ought
34  *       to enforce never leaving a completely filled block in the
35  *       puzzle as presented.
36  *
37  *  - alternative interface modes
38  *     + sudoku.com's Windows program has a palette of possible
39  *       entries; you select a palette entry first and then click
40  *       on the square you want it to go in, thus enabling
41  *       mouse-only play. Useful for PDAs! I don't think it's
42  *       actually incompatible with the current highlight-then-type
43  *       approach: you _either_ highlight a palette entry and then
44  *       click, _or_ you highlight a square and then type. At most
45  *       one thing is ever highlighted at a time, so there's no way
46  *       to confuse the two.
47  *     + then again, I don't actually like sudoku.com's interface;
48  *       it's too much like a paint package whereas I prefer to
49  *       think of Solo as a text editor.
50  *     + another PDA-friendly possibility is a drag interface:
51  *       _drag_ numbers from the palette into the grid squares.
52  *       Thought experiments suggest I'd prefer that to the
53  *       sudoku.com approach, but I haven't actually tried it.
54  */
55
56 /*
57  * Solo puzzles need to be square overall (since each row and each
58  * column must contain one of every digit), but they need not be
59  * subdivided the same way internally. I am going to adopt a
60  * convention whereby I _always_ refer to `r' as the number of rows
61  * of _big_ divisions, and `c' as the number of columns of _big_
62  * divisions. Thus, a 2c by 3r puzzle looks something like this:
63  *
64  *   4 5 1 | 2 6 3
65  *   6 3 2 | 5 4 1
66  *   ------+------     (Of course, you can't subdivide it the other way
67  *   1 4 5 | 6 3 2     or you'll get clashes; observe that the 4 in the
68  *   3 2 6 | 4 1 5     top left would conflict with the 4 in the second
69  *   ------+------     box down on the left-hand side.)
70  *   5 1 4 | 3 2 6
71  *   2 6 3 | 1 5 4
72  *
73  * The need for a strong naming convention should now be clear:
74  * each small box is two rows of digits by three columns, while the
75  * overall puzzle has three rows of small boxes by two columns. So
76  * I will (hopefully) consistently use `r' to denote the number of
77  * rows _of small boxes_ (here 3), which is also the number of
78  * columns of digits in each small box; and `c' vice versa (here
79  * 2).
80  *
81  * I'm also going to choose arbitrarily to list c first wherever
82  * possible: the above is a 2x3 puzzle, not a 3x2 one.
83  */
84
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <assert.h>
89 #include <ctype.h>
90 #include <math.h>
91
92 #ifdef STANDALONE_SOLVER
93 #include <stdarg.h>
94 int solver_show_working, solver_recurse_depth;
95 #endif
96
97 #include "puzzles.h"
98
99 /*
100  * To save space, I store digits internally as unsigned char. This
101  * imposes a hard limit of 255 on the order of the puzzle. Since
102  * even a 5x5 takes unacceptably long to generate, I don't see this
103  * as a serious limitation unless something _really_ impressive
104  * happens in computing technology; but here's a typedef anyway for
105  * general good practice.
106  */
107 typedef unsigned char digit;
108 #define ORDER_MAX 255
109
110 #define PREFERRED_TILE_SIZE 48
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113 #define GRIDEXTRA max((TILE_SIZE / 32),1)
114
115 #define FLASH_TIME 0.4F
116
117 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
118        SYMM_REF4D, SYMM_REF8 };
119
120 enum { DIFF_BLOCK,
121        DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME, DIFF_RECURSIVE,
122        DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
123
124 enum { DIFF_KSINGLE, DIFF_KMINMAX, DIFF_KSUMS, DIFF_KINTERSECT };
125
126 enum {
127     COL_BACKGROUND,
128     COL_XDIAGONALS,
129     COL_GRID,
130     COL_CLUE,
131     COL_USER,
132     COL_HIGHLIGHT,
133     COL_ERROR,
134     COL_PENCIL,
135     COL_KILLER,
136     NCOLOURS
137 };
138
139 /*
140  * To determine all possible ways to reach a given sum by adding two or
141  * three numbers from 1..9, each of which occurs exactly once in the sum,
142  * these arrays contain a list of bitmasks for each sum value, where if
143  * bit N is set, it means that N occurs in the sum.  Each list is
144  * terminated by a zero if it is shorter than the size of the array.
145  */
146 #define MAX_2SUMS 5
147 #define MAX_3SUMS 8
148 #define MAX_4SUMS 12
149 unsigned long sum_bits2[18][MAX_2SUMS];
150 unsigned long sum_bits3[25][MAX_3SUMS];
151 unsigned long sum_bits4[31][MAX_4SUMS];
152
153 static int find_sum_bits(unsigned long *array, int idx, int value_left,
154                          int addends_left, int min_addend,
155                          unsigned long bitmask_so_far)
156 {
157     int i;
158     assert(addends_left >= 2);
159
160     for (i = min_addend; i < value_left; i++) {
161         unsigned long new_bitmask = bitmask_so_far | (1L << i);
162         assert(bitmask_so_far != new_bitmask);
163
164         if (addends_left == 2) {
165             int j = value_left - i;
166             if (j <= i)
167                 break;
168             if (j > 9)
169                 continue;
170             array[idx++] = new_bitmask | (1L << j);
171         } else
172             idx = find_sum_bits(array, idx, value_left - i,
173                                 addends_left - 1, i + 1,
174                                 new_bitmask);
175     }
176     return idx;
177 }
178
179 static void precompute_sum_bits(void)
180 {
181     int i;
182     for (i = 3; i < 31; i++) {
183         int j;
184         if (i < 18) {
185             j = find_sum_bits(sum_bits2[i], 0, i, 2, 1, 0);
186             assert (j <= MAX_2SUMS);
187             if (j < MAX_2SUMS)
188                 sum_bits2[i][j] = 0;
189         }
190         if (i < 25) {
191             j = find_sum_bits(sum_bits3[i], 0, i, 3, 1, 0);
192             assert (j <= MAX_3SUMS);
193             if (j < MAX_3SUMS)
194                 sum_bits3[i][j] = 0;
195         }
196         j = find_sum_bits(sum_bits4[i], 0, i, 4, 1, 0);
197         assert (j <= MAX_4SUMS);
198         if (j < MAX_4SUMS)
199             sum_bits4[i][j] = 0;
200     }
201 }
202
203 struct game_params {
204     /*
205      * For a square puzzle, `c' and `r' indicate the puzzle
206      * parameters as described above.
207      * 
208      * A jigsaw-style puzzle is indicated by r==1, in which case c
209      * can be whatever it likes (there is no constraint on
210      * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
211      */
212     int c, r, symm, diff, kdiff;
213     int xtype;                         /* require all digits in X-diagonals */
214     int killer;
215 };
216
217 struct block_structure {
218     int refcount;
219
220     /*
221      * For text formatting, we do need c and r here.
222      */
223     int c, r, area;
224
225     /*
226      * For any square index, whichblock[i] gives its block index.
227      *
228      * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
229      * square in block b.  nr_squares[b] gives the number of squares
230      * in block b (also the number of valid elements in blocks[b]).
231      *
232      * blocks_data holds the data pointed to by blocks.
233      *
234      * nr_squares may be NULL for block structures where all blocks are
235      * the same size.
236      */
237     int *whichblock, **blocks, *nr_squares, *blocks_data;
238     int nr_blocks, max_nr_squares;
239
240 #ifdef STANDALONE_SOLVER
241     /*
242      * Textual descriptions of each block. For normal Sudoku these
243      * are of the form "(1,3)"; for jigsaw they are "starting at
244      * (5,7)". So the sensible usage in both cases is to say
245      * "elimination within block %s" with one of these strings.
246      * 
247      * Only blocknames itself needs individually freeing; it's all
248      * one block.
249      */
250     char **blocknames;
251 #endif
252 };
253
254 struct game_state {
255     /*
256      * For historical reasons, I use `cr' to denote the overall
257      * width/height of the puzzle. It was a natural notation when
258      * all puzzles were divided into blocks in a grid, but doesn't
259      * really make much sense given jigsaw puzzles. However, the
260      * obvious `n' is heavily used in the solver to describe the
261      * index of a number being placed, so `cr' will have to stay.
262      */
263     int cr;
264     struct block_structure *blocks;
265     struct block_structure *kblocks;   /* Blocks for killer puzzles.  */
266     int xtype, killer;
267     digit *grid, *kgrid;
268     unsigned char *pencil;             /* c*r*c*r elements */
269     unsigned char *immutable;          /* marks which digits are clues */
270     int completed, cheated;
271 };
272
273 static game_params *default_params(void)
274 {
275     game_params *ret = snew(game_params);
276
277     ret->c = ret->r = 3;
278     ret->xtype = FALSE;
279     ret->killer = FALSE;
280     ret->symm = SYMM_ROT2;             /* a plausible default */
281     ret->diff = DIFF_BLOCK;            /* so is this */
282     ret->kdiff = DIFF_KINTERSECT;      /* so is this */
283
284     return ret;
285 }
286
287 static void free_params(game_params *params)
288 {
289     sfree(params);
290 }
291
292 static game_params *dup_params(const game_params *params)
293 {
294     game_params *ret = snew(game_params);
295     *ret = *params;                    /* structure copy */
296     return ret;
297 }
298
299 static int game_fetch_preset(int i, char **name, game_params **params)
300 {
301     static struct {
302         const char *title;
303         game_params params;
304     } const presets[] = {
305         { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
306         { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
307         { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
308         { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
309         { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
310         { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, DIFF_KMINMAX, FALSE, FALSE } },
311         { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
312         { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, TRUE } },
313         { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, DIFF_KMINMAX, FALSE, FALSE } },
314         { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, DIFF_KMINMAX, FALSE, FALSE } },
315         { "3x3 Killer", { 3, 3, SYMM_NONE, DIFF_BLOCK, DIFF_KINTERSECT, FALSE, TRUE } },
316         { "9 Jigsaw Basic", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
317         { "9 Jigsaw Basic X", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
318         { "9 Jigsaw Advanced", { 9, 1, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
319 #ifndef SLOW_SYSTEM
320         { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
321         { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
322 #endif
323     };
324
325     if (i < 0 || i >= lenof(presets))
326         return FALSE;
327
328     *name = dupstr(presets[i].title);
329     *params = dup_params(&presets[i].params);
330
331     return TRUE;
332 }
333
334 static void decode_params(game_params *ret, char const *string)
335 {
336     int seen_r = FALSE;
337
338     ret->c = ret->r = atoi(string);
339     ret->xtype = FALSE;
340     ret->killer = FALSE;
341     while (*string && isdigit((unsigned char)*string)) string++;
342     if (*string == 'x') {
343         string++;
344         ret->r = atoi(string);
345         seen_r = TRUE;
346         while (*string && isdigit((unsigned char)*string)) string++;
347     }
348     while (*string) {
349         if (*string == 'j') {
350             string++;
351             if (seen_r)
352                 ret->c *= ret->r;
353             ret->r = 1;
354         } else if (*string == 'x') {
355             string++;
356             ret->xtype = TRUE;
357         } else if (*string == 'k') {
358             string++;
359             ret->killer = TRUE;
360         } else if (*string == 'r' || *string == 'm' || *string == 'a') {
361             int sn, sc, sd;
362             sc = *string++;
363             if (sc == 'm' && *string == 'd') {
364                 sd = TRUE;
365                 string++;
366             } else {
367                 sd = FALSE;
368             }
369             sn = atoi(string);
370             while (*string && isdigit((unsigned char)*string)) string++;
371             if (sc == 'm' && sn == 8)
372                 ret->symm = SYMM_REF8;
373             if (sc == 'm' && sn == 4)
374                 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
375             if (sc == 'm' && sn == 2)
376                 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
377             if (sc == 'r' && sn == 4)
378                 ret->symm = SYMM_ROT4;
379             if (sc == 'r' && sn == 2)
380                 ret->symm = SYMM_ROT2;
381             if (sc == 'a')
382                 ret->symm = SYMM_NONE;
383         } else if (*string == 'd') {
384             string++;
385             if (*string == 't')        /* trivial */
386                 string++, ret->diff = DIFF_BLOCK;
387             else if (*string == 'b')   /* basic */
388                 string++, ret->diff = DIFF_SIMPLE;
389             else if (*string == 'i')   /* intermediate */
390                 string++, ret->diff = DIFF_INTERSECT;
391             else if (*string == 'a')   /* advanced */
392                 string++, ret->diff = DIFF_SET;
393             else if (*string == 'e')   /* extreme */
394                 string++, ret->diff = DIFF_EXTREME;
395             else if (*string == 'u')   /* unreasonable */
396                 string++, ret->diff = DIFF_RECURSIVE;
397         } else
398             string++;                  /* eat unknown character */
399     }
400 }
401
402 static char *encode_params(const game_params *params, int full)
403 {
404     char str[80];
405
406     if (params->r > 1)
407         sprintf(str, "%dx%d", params->c, params->r);
408     else
409         sprintf(str, "%dj", params->c);
410     if (params->xtype)
411         strcat(str, "x");
412     if (params->killer)
413         strcat(str, "k");
414
415     if (full) {
416         switch (params->symm) {
417           case SYMM_REF8: strcat(str, "m8"); break;
418           case SYMM_REF4: strcat(str, "m4"); break;
419           case SYMM_REF4D: strcat(str, "md4"); break;
420           case SYMM_REF2: strcat(str, "m2"); break;
421           case SYMM_REF2D: strcat(str, "md2"); break;
422           case SYMM_ROT4: strcat(str, "r4"); break;
423           /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
424           case SYMM_NONE: strcat(str, "a"); break;
425         }
426         switch (params->diff) {
427           /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
428           case DIFF_SIMPLE: strcat(str, "db"); break;
429           case DIFF_INTERSECT: strcat(str, "di"); break;
430           case DIFF_SET: strcat(str, "da"); break;
431           case DIFF_EXTREME: strcat(str, "de"); break;
432           case DIFF_RECURSIVE: strcat(str, "du"); break;
433         }
434     }
435     return dupstr(str);
436 }
437
438 static config_item *game_configure(const game_params *params)
439 {
440     config_item *ret;
441     char buf[80];
442
443     ret = snewn(8, config_item);
444
445     ret[0].name = "Columns of sub-blocks";
446     ret[0].type = C_STRING;
447     sprintf(buf, "%d", params->c);
448     ret[0].u.string.sval = dupstr(buf);
449
450     ret[1].name = "Rows of sub-blocks";
451     ret[1].type = C_STRING;
452     sprintf(buf, "%d", params->r);
453     ret[1].u.string.sval = dupstr(buf);
454
455     ret[2].name = "\"X\" (require every number in each main diagonal)";
456     ret[2].type = C_BOOLEAN;
457     ret[2].u.boolean.bval = params->xtype;
458
459     ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
460     ret[3].type = C_BOOLEAN;
461     ret[3].u.boolean.bval = (params->r == 1);
462
463     ret[4].name = "Killer (digit sums)";
464     ret[4].type = C_BOOLEAN;
465     ret[4].u.boolean.bval = params->killer;
466
467     ret[5].name = "Symmetry";
468     ret[5].type = C_CHOICES;
469     ret[5].u.choices.choicenames = ":None:2-way rotation:4-way rotation:2-way mirror:"
470         "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
471         "8-way mirror";
472     ret[5].u.choices.selected = params->symm;
473
474     ret[6].name = "Difficulty";
475     ret[6].type = C_CHOICES;
476     ret[6].u.choices.choicenames = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
477     ret[6].u.choices.selected = params->diff;
478
479     ret[7].name = NULL;
480     ret[7].type = C_END;
481
482     return ret;
483 }
484
485 static game_params *custom_params(const config_item *cfg)
486 {
487     game_params *ret = snew(game_params);
488
489     ret->c = atoi(cfg[0].u.string.sval);
490     ret->r = atoi(cfg[1].u.string.sval);
491     ret->xtype = cfg[2].u.boolean.bval;
492     if (cfg[3].u.boolean.bval) {
493         ret->c *= ret->r;
494         ret->r = 1;
495     }
496     ret->killer = cfg[4].u.boolean.bval;
497     ret->symm = cfg[5].u.choices.selected;
498     ret->diff = cfg[6].u.choices.selected;
499     ret->kdiff = DIFF_KINTERSECT;
500
501     return ret;
502 }
503
504 static const char *validate_params(const game_params *params, int full)
505 {
506     if (params->c < 2)
507         return "Both dimensions must be at least 2";
508     if (params->c > ORDER_MAX || params->r > ORDER_MAX)
509         return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
510     if ((params->c * params->r) > 31)
511         return "Unable to support more than 31 distinct symbols in a puzzle";
512     if (params->killer && params->c * params->r > 9)
513         return "Killer puzzle dimensions must be smaller than 10.";
514     return NULL;
515 }
516
517 /*
518  * ----------------------------------------------------------------------
519  * Block structure functions.
520  */
521
522 static struct block_structure *alloc_block_structure(int c, int r, int area,
523                                                      int max_nr_squares,
524                                                      int nr_blocks)
525 {
526     int i;
527     struct block_structure *b = snew(struct block_structure);
528
529     b->refcount = 1;
530     b->nr_blocks = nr_blocks;
531     b->max_nr_squares = max_nr_squares;
532     b->c = c; b->r = r; b->area = area;
533     b->whichblock = snewn(area, int);
534     b->blocks_data = snewn(nr_blocks * max_nr_squares, int);
535     b->blocks = snewn(nr_blocks, int *);
536     b->nr_squares = snewn(nr_blocks, int);
537
538     for (i = 0; i < nr_blocks; i++)
539         b->blocks[i] = b->blocks_data + i*max_nr_squares;
540
541 #ifdef STANDALONE_SOLVER
542     b->blocknames = (char **)smalloc(c*r*(sizeof(char *)+80));
543     for (i = 0; i < c * r; i++)
544         b->blocknames[i] = NULL;
545 #endif
546     return b;
547 }
548
549 static void free_block_structure(struct block_structure *b)
550 {
551     if (--b->refcount == 0) {
552         sfree(b->whichblock);
553         sfree(b->blocks);
554         sfree(b->blocks_data);
555 #ifdef STANDALONE_SOLVER
556         sfree(b->blocknames);
557 #endif
558         sfree(b->nr_squares);
559         sfree(b);
560     }
561 }
562
563 static struct block_structure *dup_block_structure(struct block_structure *b)
564 {
565     struct block_structure *nb;
566     int i;
567
568     nb = alloc_block_structure(b->c, b->r, b->area, b->max_nr_squares,
569                                b->nr_blocks);
570     memcpy(nb->nr_squares, b->nr_squares, b->nr_blocks * sizeof *b->nr_squares);
571     memcpy(nb->whichblock, b->whichblock, b->area * sizeof *b->whichblock);
572     memcpy(nb->blocks_data, b->blocks_data,
573            b->nr_blocks * b->max_nr_squares * sizeof *b->blocks_data);
574     for (i = 0; i < b->nr_blocks; i++)
575         nb->blocks[i] = nb->blocks_data + i*nb->max_nr_squares;
576
577 #ifdef STANDALONE_SOLVER
578     memcpy(nb->blocknames, b->blocknames, b->c * b->r *(sizeof(char *)+80));
579     {
580         int i;
581         for (i = 0; i < b->c * b->r; i++)
582             if (b->blocknames[i] == NULL)
583                 nb->blocknames[i] = NULL;
584             else
585                 nb->blocknames[i] = ((char *)nb->blocknames) + (b->blocknames[i] - (char *)b->blocknames);
586     }
587 #endif
588     return nb;
589 }
590
591 static void split_block(struct block_structure *b, int *squares, int nr_squares)
592 {
593     int i, j;
594     int previous_block = b->whichblock[squares[0]];
595     int newblock = b->nr_blocks;
596
597     assert(b->max_nr_squares >= nr_squares);
598     assert(b->nr_squares[previous_block] > nr_squares);
599
600     b->nr_blocks++;
601     b->blocks_data = sresize(b->blocks_data,
602                              b->nr_blocks * b->max_nr_squares, int);
603     b->nr_squares = sresize(b->nr_squares, b->nr_blocks, int);
604     sfree(b->blocks);
605     b->blocks = snewn(b->nr_blocks, int *);
606     for (i = 0; i < b->nr_blocks; i++)
607         b->blocks[i] = b->blocks_data + i*b->max_nr_squares;
608     for (i = 0; i < nr_squares; i++) {
609         assert(b->whichblock[squares[i]] == previous_block);
610         b->whichblock[squares[i]] = newblock;
611         b->blocks[newblock][i] = squares[i];
612     }
613     for (i = j = 0; i < b->nr_squares[previous_block]; i++) {
614         int k;
615         int sq = b->blocks[previous_block][i];
616         for (k = 0; k < nr_squares; k++)
617             if (squares[k] == sq)
618                 break;
619         if (k == nr_squares)
620             b->blocks[previous_block][j++] = sq;
621     }
622     b->nr_squares[previous_block] -= nr_squares;
623     b->nr_squares[newblock] = nr_squares;
624 }
625
626 static void remove_from_block(struct block_structure *blocks, int b, int n)
627 {
628     int i, j;
629     blocks->whichblock[n] = -1;
630     for (i = j = 0; i < blocks->nr_squares[b]; i++)
631         if (blocks->blocks[b][i] != n)
632             blocks->blocks[b][j++] = blocks->blocks[b][i];
633     assert(j+1 == i);
634     blocks->nr_squares[b]--;
635 }
636
637 /* ----------------------------------------------------------------------
638  * Solver.
639  * 
640  * This solver is used for two purposes:
641  *  + to check solubility of a grid as we gradually remove numbers
642  *    from it
643  *  + to solve an externally generated puzzle when the user selects
644  *    `Solve'.
645  * 
646  * It supports a variety of specific modes of reasoning. By
647  * enabling or disabling subsets of these modes we can arrange a
648  * range of difficulty levels.
649  */
650
651 /*
652  * Modes of reasoning currently supported:
653  *
654  *  - Positional elimination: a number must go in a particular
655  *    square because all the other empty squares in a given
656  *    row/col/blk are ruled out.
657  *
658  *  - Killer minmax elimination: for killer-type puzzles, a number
659  *    is impossible if choosing it would cause the sum in a killer
660  *    region to be guaranteed to be too large or too small.
661  *
662  *  - Numeric elimination: a square must have a particular number
663  *    in because all the other numbers that could go in it are
664  *    ruled out.
665  *
666  *  - Intersectional analysis: given two domains which overlap
667  *    (hence one must be a block, and the other can be a row or
668  *    col), if the possible locations for a particular number in
669  *    one of the domains can be narrowed down to the overlap, then
670  *    that number can be ruled out everywhere but the overlap in
671  *    the other domain too.
672  *
673  *  - Set elimination: if there is a subset of the empty squares
674  *    within a domain such that the union of the possible numbers
675  *    in that subset has the same size as the subset itself, then
676  *    those numbers can be ruled out everywhere else in the domain.
677  *    (For example, if there are five empty squares and the
678  *    possible numbers in each are 12, 23, 13, 134 and 1345, then
679  *    the first three empty squares form such a subset: the numbers
680  *    1, 2 and 3 _must_ be in those three squares in some
681  *    permutation, and hence we can deduce none of them can be in
682  *    the fourth or fifth squares.)
683  *     + You can also see this the other way round, concentrating
684  *       on numbers rather than squares: if there is a subset of
685  *       the unplaced numbers within a domain such that the union
686  *       of all their possible positions has the same size as the
687  *       subset itself, then all other numbers can be ruled out for
688  *       those positions. However, it turns out that this is
689  *       exactly equivalent to the first formulation at all times:
690  *       there is a 1-1 correspondence between suitable subsets of
691  *       the unplaced numbers and suitable subsets of the unfilled
692  *       places, found by taking the _complement_ of the union of
693  *       the numbers' possible positions (or the spaces' possible
694  *       contents).
695  * 
696  *  - Forcing chains (see comment for solver_forcing().)
697  * 
698  *  - Recursion. If all else fails, we pick one of the currently
699  *    most constrained empty squares and take a random guess at its
700  *    contents, then continue solving on that basis and see if we
701  *    get any further.
702  */
703
704 struct solver_usage {
705     int cr;
706     struct block_structure *blocks, *kblocks, *extra_cages;
707     /*
708      * We set up a cubic array, indexed by x, y and digit; each
709      * element of this array is TRUE or FALSE according to whether
710      * or not that digit _could_ in principle go in that position.
711      *
712      * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
713      * are macros below to help with this.
714      */
715     unsigned char *cube;
716     /*
717      * This is the grid in which we write down our final
718      * deductions. y-coordinates in here are _not_ transformed.
719      */
720     digit *grid;
721     /*
722      * For killer-type puzzles, kclues holds the secondary clue for
723      * each cage.  For derived cages, the clue is in extra_clues.
724      */
725     digit *kclues, *extra_clues;
726     /*
727      * Now we keep track, at a slightly higher level, of what we
728      * have yet to work out, to prevent doing the same deduction
729      * many times.
730      */
731     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
732     unsigned char *row;
733     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
734     unsigned char *col;
735     /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
736     unsigned char *blk;
737     /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
738     unsigned char *diag;               /* diag 0 is \, 1 is / */
739
740     int *regions;
741     int nr_regions;
742     int **sq2region;
743 };
744 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
745 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
746 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
747 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
748
749 #define ondiag0(xy) ((xy) % (cr+1) == 0)
750 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
751 #define diag0(i) ((i) * (cr+1))
752 #define diag1(i) ((i+1) * (cr-1))
753
754 /*
755  * Function called when we are certain that a particular square has
756  * a particular number in it. The y-coordinate passed in here is
757  * transformed.
758  */
759 static void solver_place(struct solver_usage *usage, int x, int y, int n)
760 {
761     int cr = usage->cr;
762     int sqindex = y*cr+x;
763     int i, bi;
764
765     assert(cube(x,y,n));
766
767     /*
768      * Rule out all other numbers in this square.
769      */
770     for (i = 1; i <= cr; i++)
771         if (i != n)
772             cube(x,y,i) = FALSE;
773
774     /*
775      * Rule out this number in all other positions in the row.
776      */
777     for (i = 0; i < cr; i++)
778         if (i != y)
779             cube(x,i,n) = FALSE;
780
781     /*
782      * Rule out this number in all other positions in the column.
783      */
784     for (i = 0; i < cr; i++)
785         if (i != x)
786             cube(i,y,n) = FALSE;
787
788     /*
789      * Rule out this number in all other positions in the block.
790      */
791     bi = usage->blocks->whichblock[sqindex];
792     for (i = 0; i < cr; i++) {
793         int bp = usage->blocks->blocks[bi][i];
794         if (bp != sqindex)
795             cube2(bp,n) = FALSE;
796     }
797
798     /*
799      * Enter the number in the result grid.
800      */
801     usage->grid[sqindex] = n;
802
803     /*
804      * Cross out this number from the list of numbers left to place
805      * in its row, its column and its block.
806      */
807     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
808         usage->blk[bi*cr+n-1] = TRUE;
809
810     if (usage->diag) {
811         if (ondiag0(sqindex)) {
812             for (i = 0; i < cr; i++)
813                 if (diag0(i) != sqindex)
814                     cube2(diag0(i),n) = FALSE;
815             usage->diag[n-1] = TRUE;
816         }
817         if (ondiag1(sqindex)) {
818             for (i = 0; i < cr; i++)
819                 if (diag1(i) != sqindex)
820                     cube2(diag1(i),n) = FALSE;
821             usage->diag[cr+n-1] = TRUE;
822         }
823     }
824 }
825
826 #if defined STANDALONE_SOLVER && defined __GNUC__
827 /*
828  * Forward-declare the functions taking printf-like format arguments
829  * with __attribute__((format)) so as to ensure the argument syntax
830  * gets debugged.
831  */
832 struct solver_scratch;
833 static int solver_elim(struct solver_usage *usage, int *indices,
834                        const char *fmt, ...)
835     __attribute__((format(printf,3,4)));
836 static int solver_intersect(struct solver_usage *usage,
837                             int *indices1, int *indices2, const char *fmt, ...)
838     __attribute__((format(printf,4,5)));
839 static int solver_set(struct solver_usage *usage,
840                       struct solver_scratch *scratch,
841                       int *indices, const char *fmt, ...)
842     __attribute__((format(printf,4,5)));
843 #endif
844
845 static int solver_elim(struct solver_usage *usage, int *indices
846 #ifdef STANDALONE_SOLVER
847                        , const char *fmt, ...
848 #endif
849                        )
850 {
851     int cr = usage->cr;
852     int fpos, m, i;
853
854     /*
855      * Count the number of set bits within this section of the
856      * cube.
857      */
858     m = 0;
859     fpos = -1;
860     for (i = 0; i < cr; i++)
861         if (usage->cube[indices[i]]) {
862             fpos = indices[i];
863             m++;
864         }
865
866     if (m == 1) {
867         int x, y, n;
868         assert(fpos >= 0);
869
870         n = 1 + fpos % cr;
871         x = fpos / cr;
872         y = x / cr;
873         x %= cr;
874
875         if (!usage->grid[y*cr+x]) {
876 #ifdef STANDALONE_SOLVER
877             if (solver_show_working) {
878                 va_list ap;
879                 printf("%*s", solver_recurse_depth*4, "");
880                 va_start(ap, fmt);
881                 vprintf(fmt, ap);
882                 va_end(ap);
883                 printf(":\n%*s  placing %d at (%d,%d)\n",
884                        solver_recurse_depth*4, "", n, 1+x, 1+y);
885             }
886 #endif
887             solver_place(usage, x, y, n);
888             return +1;
889         }
890     } else if (m == 0) {
891 #ifdef STANDALONE_SOLVER
892         if (solver_show_working) {
893             va_list ap;
894             printf("%*s", solver_recurse_depth*4, "");
895             va_start(ap, fmt);
896             vprintf(fmt, ap);
897             va_end(ap);
898             printf(":\n%*s  no possibilities available\n",
899                    solver_recurse_depth*4, "");
900         }
901 #endif
902         return -1;
903     }
904
905     return 0;
906 }
907
908 static int solver_intersect(struct solver_usage *usage,
909                             int *indices1, int *indices2
910 #ifdef STANDALONE_SOLVER
911                             , const char *fmt, ...
912 #endif
913                             )
914 {
915     int cr = usage->cr;
916     int ret, i, j;
917
918     /*
919      * Loop over the first domain and see if there's any set bit
920      * not also in the second.
921      */
922     for (i = j = 0; i < cr; i++) {
923         int p = indices1[i];
924         while (j < cr && indices2[j] < p)
925             j++;
926         if (usage->cube[p]) {
927             if (j < cr && indices2[j] == p)
928                 continue;              /* both domains contain this index */
929             else
930                 return 0;              /* there is, so we can't deduce */
931         }
932     }
933
934     /*
935      * We have determined that all set bits in the first domain are
936      * within its overlap with the second. So loop over the second
937      * domain and remove all set bits that aren't also in that
938      * overlap; return +1 iff we actually _did_ anything.
939      */
940     ret = 0;
941     for (i = j = 0; i < cr; i++) {
942         int p = indices2[i];
943         while (j < cr && indices1[j] < p)
944             j++;
945         if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
946 #ifdef STANDALONE_SOLVER
947             if (solver_show_working) {
948                 int px, py, pn;
949
950                 if (!ret) {
951                     va_list ap;
952                     printf("%*s", solver_recurse_depth*4, "");
953                     va_start(ap, fmt);
954                     vprintf(fmt, ap);
955                     va_end(ap);
956                     printf(":\n");
957                 }
958
959                 pn = 1 + p % cr;
960                 px = p / cr;
961                 py = px / cr;
962                 px %= cr;
963
964                 printf("%*s  ruling out %d at (%d,%d)\n",
965                        solver_recurse_depth*4, "", pn, 1+px, 1+py);
966             }
967 #endif
968             ret = +1;                  /* we did something */
969             usage->cube[p] = 0;
970         }
971     }
972
973     return ret;
974 }
975
976 struct solver_scratch {
977     unsigned char *grid, *rowidx, *colidx, *set;
978     int *neighbours, *bfsqueue;
979     int *indexlist, *indexlist2;
980 #ifdef STANDALONE_SOLVER
981     int *bfsprev;
982 #endif
983 };
984
985 static int solver_set(struct solver_usage *usage,
986                       struct solver_scratch *scratch,
987                       int *indices
988 #ifdef STANDALONE_SOLVER
989                       , const char *fmt, ...
990 #endif
991                       )
992 {
993     int cr = usage->cr;
994     int i, j, n, count;
995     unsigned char *grid = scratch->grid;
996     unsigned char *rowidx = scratch->rowidx;
997     unsigned char *colidx = scratch->colidx;
998     unsigned char *set = scratch->set;
999
1000     /*
1001      * We are passed a cr-by-cr matrix of booleans. Our first job
1002      * is to winnow it by finding any definite placements - i.e.
1003      * any row with a solitary 1 - and discarding that row and the
1004      * column containing the 1.
1005      */
1006     memset(rowidx, TRUE, cr);
1007     memset(colidx, TRUE, cr);
1008     for (i = 0; i < cr; i++) {
1009         int count = 0, first = -1;
1010         for (j = 0; j < cr; j++)
1011             if (usage->cube[indices[i*cr+j]])
1012                 first = j, count++;
1013
1014         /*
1015          * If count == 0, then there's a row with no 1s at all and
1016          * the puzzle is internally inconsistent. However, we ought
1017          * to have caught this already during the simpler reasoning
1018          * methods, so we can safely fail an assertion if we reach
1019          * this point here.
1020          */
1021         assert(count > 0);
1022         if (count == 1)
1023             rowidx[i] = colidx[first] = FALSE;
1024     }
1025
1026     /*
1027      * Convert each of rowidx/colidx from a list of 0s and 1s to a
1028      * list of the indices of the 1s.
1029      */
1030     for (i = j = 0; i < cr; i++)
1031         if (rowidx[i])
1032             rowidx[j++] = i;
1033     n = j;
1034     for (i = j = 0; i < cr; i++)
1035         if (colidx[i])
1036             colidx[j++] = i;
1037     assert(n == j);
1038
1039     /*
1040      * And create the smaller matrix.
1041      */
1042     for (i = 0; i < n; i++)
1043         for (j = 0; j < n; j++)
1044             grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
1045
1046     /*
1047      * Having done that, we now have a matrix in which every row
1048      * has at least two 1s in. Now we search to see if we can find
1049      * a rectangle of zeroes (in the set-theoretic sense of
1050      * `rectangle', i.e. a subset of rows crossed with a subset of
1051      * columns) whose width and height add up to n.
1052      */
1053
1054     memset(set, 0, n);
1055     count = 0;
1056     while (1) {
1057         /*
1058          * We have a candidate set. If its size is <=1 or >=n-1
1059          * then we move on immediately.
1060          */
1061         if (count > 1 && count < n-1) {
1062             /*
1063              * The number of rows we need is n-count. See if we can
1064              * find that many rows which each have a zero in all
1065              * the positions listed in `set'.
1066              */
1067             int rows = 0;
1068             for (i = 0; i < n; i++) {
1069                 int ok = TRUE;
1070                 for (j = 0; j < n; j++)
1071                     if (set[j] && grid[i*cr+j]) {
1072                         ok = FALSE;
1073                         break;
1074                     }
1075                 if (ok)
1076                     rows++;
1077             }
1078
1079             /*
1080              * We expect never to be able to get _more_ than
1081              * n-count suitable rows: this would imply that (for
1082              * example) there are four numbers which between them
1083              * have at most three possible positions, and hence it
1084              * indicates a faulty deduction before this point or
1085              * even a bogus clue.
1086              */
1087             if (rows > n - count) {
1088 #ifdef STANDALONE_SOLVER
1089                 if (solver_show_working) {
1090                     va_list ap;
1091                     printf("%*s", solver_recurse_depth*4,
1092                            "");
1093                     va_start(ap, fmt);
1094                     vprintf(fmt, ap);
1095                     va_end(ap);
1096                     printf(":\n%*s  contradiction reached\n",
1097                            solver_recurse_depth*4, "");
1098                 }
1099 #endif
1100                 return -1;
1101             }
1102
1103             if (rows >= n - count) {
1104                 int progress = FALSE;
1105
1106                 /*
1107                  * We've got one! Now, for each row which _doesn't_
1108                  * satisfy the criterion, eliminate all its set
1109                  * bits in the positions _not_ listed in `set'.
1110                  * Return +1 (meaning progress has been made) if we
1111                  * successfully eliminated anything at all.
1112                  * 
1113                  * This involves referring back through
1114                  * rowidx/colidx in order to work out which actual
1115                  * positions in the cube to meddle with.
1116                  */
1117                 for (i = 0; i < n; i++) {
1118                     int ok = TRUE;
1119                     for (j = 0; j < n; j++)
1120                         if (set[j] && grid[i*cr+j]) {
1121                             ok = FALSE;
1122                             break;
1123                         }
1124                     if (!ok) {
1125                         for (j = 0; j < n; j++)
1126                             if (!set[j] && grid[i*cr+j]) {
1127                                 int fpos = indices[rowidx[i]*cr+colidx[j]];
1128 #ifdef STANDALONE_SOLVER
1129                                 if (solver_show_working) {
1130                                     int px, py, pn;
1131
1132                                     if (!progress) {
1133                                         va_list ap;
1134                                         printf("%*s", solver_recurse_depth*4,
1135                                                "");
1136                                         va_start(ap, fmt);
1137                                         vprintf(fmt, ap);
1138                                         va_end(ap);
1139                                         printf(":\n");
1140                                     }
1141
1142                                     pn = 1 + fpos % cr;
1143                                     px = fpos / cr;
1144                                     py = px / cr;
1145                                     px %= cr;
1146
1147                                     printf("%*s  ruling out %d at (%d,%d)\n",
1148                                            solver_recurse_depth*4, "",
1149                                            pn, 1+px, 1+py);
1150                                 }
1151 #endif
1152                                 progress = TRUE;
1153                                 usage->cube[fpos] = FALSE;
1154                             }
1155                     }
1156                 }
1157
1158                 if (progress) {
1159                     return +1;
1160                 }
1161             }
1162         }
1163
1164         /*
1165          * Binary increment: change the rightmost 0 to a 1, and
1166          * change all 1s to the right of it to 0s.
1167          */
1168         i = n;
1169         while (i > 0 && set[i-1])
1170             set[--i] = 0, count--;
1171         if (i > 0)
1172             set[--i] = 1, count++;
1173         else
1174             break;                     /* done */
1175     }
1176
1177     return 0;
1178 }
1179
1180 /*
1181  * Look for forcing chains. A forcing chain is a path of
1182  * pairwise-exclusive squares (i.e. each pair of adjacent squares
1183  * in the path are in the same row, column or block) with the
1184  * following properties:
1185  *
1186  *  (a) Each square on the path has precisely two possible numbers.
1187  *
1188  *  (b) Each pair of squares which are adjacent on the path share
1189  *      at least one possible number in common.
1190  *
1191  *  (c) Each square in the middle of the path shares _both_ of its
1192  *      numbers with at least one of its neighbours (not the same
1193  *      one with both neighbours).
1194  *
1195  * These together imply that at least one of the possible number
1196  * choices at one end of the path forces _all_ the rest of the
1197  * numbers along the path. In order to make real use of this, we
1198  * need further properties:
1199  *
1200  *  (c) Ruling out some number N from the square at one end of the
1201  *      path forces the square at the other end to take the same
1202  *      number N.
1203  *
1204  *  (d) The two end squares are both in line with some third
1205  *      square.
1206  *
1207  *  (e) That third square currently has N as a possibility.
1208  *
1209  * If we can find all of that lot, we can deduce that at least one
1210  * of the two ends of the forcing chain has number N, and that
1211  * therefore the mutually adjacent third square does not.
1212  *
1213  * To find forcing chains, we're going to start a bfs at each
1214  * suitable square, once for each of its two possible numbers.
1215  */
1216 static int solver_forcing(struct solver_usage *usage,
1217                           struct solver_scratch *scratch)
1218 {
1219     int cr = usage->cr;
1220     int *bfsqueue = scratch->bfsqueue;
1221 #ifdef STANDALONE_SOLVER
1222     int *bfsprev = scratch->bfsprev;
1223 #endif
1224     unsigned char *number = scratch->grid;
1225     int *neighbours = scratch->neighbours;
1226     int x, y;
1227
1228     for (y = 0; y < cr; y++)
1229         for (x = 0; x < cr; x++) {
1230             int count, t, n;
1231
1232             /*
1233              * If this square doesn't have exactly two candidate
1234              * numbers, don't try it.
1235              * 
1236              * In this loop we also sum the candidate numbers,
1237              * which is a nasty hack to allow us to quickly find
1238              * `the other one' (since we will shortly know there
1239              * are exactly two).
1240              */
1241             for (count = t = 0, n = 1; n <= cr; n++)
1242                 if (cube(x, y, n))
1243                     count++, t += n;
1244             if (count != 2)
1245                 continue;
1246
1247             /*
1248              * Now attempt a bfs for each candidate.
1249              */
1250             for (n = 1; n <= cr; n++)
1251                 if (cube(x, y, n)) {
1252                     int orign, currn, head, tail;
1253
1254                     /*
1255                      * Begin a bfs.
1256                      */
1257                     orign = n;
1258
1259                     memset(number, cr+1, cr*cr);
1260                     head = tail = 0;
1261                     bfsqueue[tail++] = y*cr+x;
1262 #ifdef STANDALONE_SOLVER
1263                     bfsprev[y*cr+x] = -1;
1264 #endif
1265                     number[y*cr+x] = t - n;
1266
1267                     while (head < tail) {
1268                         int xx, yy, nneighbours, xt, yt, i;
1269
1270                         xx = bfsqueue[head++];
1271                         yy = xx / cr;
1272                         xx %= cr;
1273
1274                         currn = number[yy*cr+xx];
1275
1276                         /*
1277                          * Find neighbours of yy,xx.
1278                          */
1279                         nneighbours = 0;
1280                         for (yt = 0; yt < cr; yt++)
1281                             neighbours[nneighbours++] = yt*cr+xx;
1282                         for (xt = 0; xt < cr; xt++)
1283                             neighbours[nneighbours++] = yy*cr+xt;
1284                         xt = usage->blocks->whichblock[yy*cr+xx];
1285                         for (yt = 0; yt < cr; yt++)
1286                             neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1287                         if (usage->diag) {
1288                             int sqindex = yy*cr+xx;
1289                             if (ondiag0(sqindex)) {
1290                                 for (i = 0; i < cr; i++)
1291                                     neighbours[nneighbours++] = diag0(i);
1292                             }
1293                             if (ondiag1(sqindex)) {
1294                                 for (i = 0; i < cr; i++)
1295                                     neighbours[nneighbours++] = diag1(i);
1296                             }
1297                         }
1298
1299                         /*
1300                          * Try visiting each of those neighbours.
1301                          */
1302                         for (i = 0; i < nneighbours; i++) {
1303                             int cc, tt, nn;
1304
1305                             xt = neighbours[i] % cr;
1306                             yt = neighbours[i] / cr;
1307
1308                             /*
1309                              * We need this square to not be
1310                              * already visited, and to include
1311                              * currn as a possible number.
1312                              */
1313                             if (number[yt*cr+xt] <= cr)
1314                                 continue;
1315                             if (!cube(xt, yt, currn))
1316                                 continue;
1317
1318                             /*
1319                              * Don't visit _this_ square a second
1320                              * time!
1321                              */
1322                             if (xt == xx && yt == yy)
1323                                 continue;
1324
1325                             /*
1326                              * To continue with the bfs, we need
1327                              * this square to have exactly two
1328                              * possible numbers.
1329                              */
1330                             for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1331                                 if (cube(xt, yt, nn))
1332                                     cc++, tt += nn;
1333                             if (cc == 2) {
1334                                 bfsqueue[tail++] = yt*cr+xt;
1335 #ifdef STANDALONE_SOLVER
1336                                 bfsprev[yt*cr+xt] = yy*cr+xx;
1337 #endif
1338                                 number[yt*cr+xt] = tt - currn;
1339                             }
1340
1341                             /*
1342                              * One other possibility is that this
1343                              * might be the square in which we can
1344                              * make a real deduction: if it's
1345                              * adjacent to x,y, and currn is equal
1346                              * to the original number we ruled out.
1347                              */
1348                             if (currn == orign &&
1349                                 (xt == x || yt == y ||
1350                                  (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1351                                  (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1352                                                   (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1353 #ifdef STANDALONE_SOLVER
1354                                 if (solver_show_working) {
1355                                     const char *sep = "";
1356                                     int xl, yl;
1357                                     printf("%*sforcing chain, %d at ends of ",
1358                                            solver_recurse_depth*4, "", orign);
1359                                     xl = xx;
1360                                     yl = yy;
1361                                     while (1) {
1362                                         printf("%s(%d,%d)", sep, 1+xl,
1363                                                1+yl);
1364                                         xl = bfsprev[yl*cr+xl];
1365                                         if (xl < 0)
1366                                             break;
1367                                         yl = xl / cr;
1368                                         xl %= cr;
1369                                         sep = "-";
1370                                     }
1371                                     printf("\n%*s  ruling out %d at (%d,%d)\n",
1372                                            solver_recurse_depth*4, "",
1373                                            orign, 1+xt, 1+yt);
1374                                 }
1375 #endif
1376                                 cube(xt, yt, orign) = FALSE;
1377                                 return 1;
1378                             }
1379                         }
1380                     }
1381                 }
1382         }
1383
1384     return 0;
1385 }
1386
1387 static int solver_killer_minmax(struct solver_usage *usage,
1388                                 struct block_structure *cages, digit *clues,
1389                                 int b
1390 #ifdef STANDALONE_SOLVER
1391                                 , const char *extra
1392 #endif
1393                                 )
1394 {
1395     int cr = usage->cr;
1396     int i;
1397     int ret = 0;
1398     int nsquares = cages->nr_squares[b];
1399
1400     if (clues[b] == 0)
1401         return 0;
1402
1403     for (i = 0; i < nsquares; i++) {
1404         int n, x = cages->blocks[b][i];
1405
1406         for (n = 1; n <= cr; n++)
1407             if (cube2(x, n)) {
1408                 int maxval = 0, minval = 0;
1409                 int j;
1410                 for (j = 0; j < nsquares; j++) {
1411                     int m;
1412                     int y = cages->blocks[b][j];
1413                     if (i == j)
1414                         continue;
1415                     for (m = 1; m <= cr; m++)
1416                         if (cube2(y, m)) {
1417                             minval += m;
1418                             break;
1419                         }
1420                     for (m = cr; m > 0; m--)
1421                         if (cube2(y, m)) {
1422                             maxval += m;
1423                             break;
1424                         }
1425                 }
1426                 if (maxval + n < clues[b]) {
1427                     cube2(x, n) = FALSE;
1428                     ret = 1;
1429 #ifdef STANDALONE_SOLVER
1430                     if (solver_show_working)
1431                         printf("%*s  ruling out %d at (%d,%d) as too low %s\n",
1432                                solver_recurse_depth*4, "killer minmax analysis",
1433                                n, 1 + x%cr, 1 + x/cr, extra);
1434 #endif
1435                 }
1436                 if (minval + n > clues[b]) {
1437                     cube2(x, n) = FALSE;
1438                     ret = 1;
1439 #ifdef STANDALONE_SOLVER
1440                     if (solver_show_working)
1441                         printf("%*s  ruling out %d at (%d,%d) as too high %s\n",
1442                                solver_recurse_depth*4, "killer minmax analysis",
1443                                n, 1 + x%cr, 1 + x/cr, extra);
1444 #endif
1445                 }
1446             }
1447     }
1448     return ret;
1449 }
1450
1451 static int solver_killer_sums(struct solver_usage *usage, int b,
1452                               struct block_structure *cages, int clue,
1453                               int cage_is_region
1454 #ifdef STANDALONE_SOLVER
1455                               , const char *cage_type
1456 #endif
1457                               )
1458 {
1459     int cr = usage->cr;
1460     int i, ret, max_sums;
1461     int nsquares = cages->nr_squares[b];
1462     unsigned long *sumbits, possible_addends;
1463
1464     if (clue == 0) {
1465         assert(nsquares == 0);
1466         return 0;
1467     }
1468     assert(nsquares > 0);
1469
1470     if (nsquares < 2 || nsquares > 4)
1471         return 0;
1472
1473     if (!cage_is_region) {
1474         int known_row = -1, known_col = -1, known_block = -1;
1475         /*
1476          * Verify that the cage lies entirely within one region,
1477          * so that using the precomputed sums is valid.
1478          */
1479         for (i = 0; i < nsquares; i++) {
1480             int x = cages->blocks[b][i];
1481
1482             assert(usage->grid[x] == 0);
1483
1484             if (i == 0) {
1485                 known_row = x/cr;
1486                 known_col = x%cr;
1487                 known_block = usage->blocks->whichblock[x];
1488             } else {
1489                 if (known_row != x/cr)
1490                     known_row = -1;
1491                 if (known_col != x%cr)
1492                     known_col = -1;
1493                 if (known_block != usage->blocks->whichblock[x])
1494                     known_block = -1;
1495             }
1496         }
1497         if (known_block == -1 && known_col == -1 && known_row == -1)
1498             return 0;
1499     }
1500     if (nsquares == 2) {
1501         if (clue < 3 || clue > 17)
1502             return -1;
1503
1504         sumbits = sum_bits2[clue];
1505         max_sums = MAX_2SUMS;
1506     } else if (nsquares == 3) {
1507         if (clue < 6 || clue > 24)
1508             return -1;
1509
1510         sumbits = sum_bits3[clue];
1511         max_sums = MAX_3SUMS;
1512     } else {
1513         if (clue < 10 || clue > 30)
1514             return -1;
1515
1516         sumbits = sum_bits4[clue];
1517         max_sums = MAX_4SUMS;
1518     }
1519     /*
1520      * For every possible way to get the sum, see if there is
1521      * one square in the cage that disallows all the required
1522      * addends.  If we find one such square, this way to compute
1523      * the sum is impossible.
1524      */
1525     possible_addends = 0;
1526     for (i = 0; i < max_sums; i++) {
1527         int j;
1528         unsigned long bits = sumbits[i];
1529
1530         if (bits == 0)
1531             break;
1532
1533         for (j = 0; j < nsquares; j++) {
1534             int n;
1535             unsigned long square_bits = bits;
1536             int x = cages->blocks[b][j];
1537             for (n = 1; n <= cr; n++)
1538                 if (!cube2(x, n))
1539                     square_bits &= ~(1L << n);
1540             if (square_bits == 0) {
1541                 break;
1542             }
1543         }
1544         if (j == nsquares)
1545             possible_addends |= bits;
1546     }
1547     /*
1548      * Now we know which addends can possibly be used to
1549      * compute the sum.  Remove all other digits from the
1550      * set of possibilities.
1551      */
1552     if (possible_addends == 0)
1553         return -1;
1554
1555     ret = 0;
1556     for (i = 0; i < nsquares; i++) {
1557         int n;
1558         int x = cages->blocks[b][i];
1559         for (n = 1; n <= cr; n++) {
1560             if (!cube2(x, n))
1561                 continue;
1562             if ((possible_addends & (1 << n)) == 0) {
1563                 cube2(x, n) = FALSE;
1564                 ret = 1;
1565 #ifdef STANDALONE_SOLVER
1566                 if (solver_show_working) {
1567                     printf("%*s  using %s\n",
1568                            solver_recurse_depth*4, "killer sums analysis",
1569                            cage_type);
1570                     printf("%*s  ruling out %d at (%d,%d) due to impossible %d-sum\n",
1571                            solver_recurse_depth*4, "",
1572                            n, 1 + x%cr, 1 + x/cr, nsquares);
1573                 }
1574 #endif
1575             }
1576         }
1577     }
1578     return ret;
1579 }
1580
1581 static int filter_whole_cages(struct solver_usage *usage, int *squares, int n,
1582                               int *filtered_sum)
1583 {
1584     int b, i, j, off;
1585     *filtered_sum = 0;
1586
1587     /* First, filter squares with a clue.  */
1588     for (i = j = 0; i < n; i++)
1589         if (usage->grid[squares[i]])
1590             *filtered_sum += usage->grid[squares[i]];
1591         else
1592             squares[j++] = squares[i];
1593     n = j;
1594
1595     /*
1596      * Filter all cages that are covered entirely by the list of
1597      * squares.
1598      */
1599     off = 0;
1600     for (b = 0; b < usage->kblocks->nr_blocks && off < n; b++) {
1601         int b_squares = usage->kblocks->nr_squares[b];
1602         int matched = 0;
1603
1604         if (b_squares == 0)
1605             continue;
1606
1607         /*
1608          * Find all squares of block b that lie in our list,
1609          * and make them contiguous at off, which is the current position
1610          * in the output list.
1611          */
1612         for (i = 0; i < b_squares; i++) {
1613             for (j = off; j < n; j++)
1614                 if (squares[j] == usage->kblocks->blocks[b][i]) {
1615                     int t = squares[off + matched];
1616                     squares[off + matched] = squares[j];
1617                     squares[j] = t;
1618                     matched++;
1619                     break;
1620                 }
1621         }
1622         /* If so, filter out all squares of b from the list.  */
1623         if (matched != usage->kblocks->nr_squares[b]) {
1624             off += matched;
1625             continue;
1626         }
1627         memmove(squares + off, squares + off + matched,
1628                 (n - off - matched) * sizeof *squares);
1629         n -= matched;
1630
1631         *filtered_sum += usage->kclues[b];
1632     }
1633     assert(off == n);
1634     return off;
1635 }
1636
1637 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1638 {
1639     struct solver_scratch *scratch = snew(struct solver_scratch);
1640     int cr = usage->cr;
1641     scratch->grid = snewn(cr*cr, unsigned char);
1642     scratch->rowidx = snewn(cr, unsigned char);
1643     scratch->colidx = snewn(cr, unsigned char);
1644     scratch->set = snewn(cr, unsigned char);
1645     scratch->neighbours = snewn(5*cr, int);
1646     scratch->bfsqueue = snewn(cr*cr, int);
1647 #ifdef STANDALONE_SOLVER
1648     scratch->bfsprev = snewn(cr*cr, int);
1649 #endif
1650     scratch->indexlist = snewn(cr*cr, int);   /* used for set elimination */
1651     scratch->indexlist2 = snewn(cr, int);   /* only used for intersect() */
1652     return scratch;
1653 }
1654
1655 static void solver_free_scratch(struct solver_scratch *scratch)
1656 {
1657 #ifdef STANDALONE_SOLVER
1658     sfree(scratch->bfsprev);
1659 #endif
1660     sfree(scratch->bfsqueue);
1661     sfree(scratch->neighbours);
1662     sfree(scratch->set);
1663     sfree(scratch->colidx);
1664     sfree(scratch->rowidx);
1665     sfree(scratch->grid);
1666     sfree(scratch->indexlist);
1667     sfree(scratch->indexlist2);
1668     sfree(scratch);
1669 }
1670
1671 /*
1672  * Used for passing information about difficulty levels between the solver
1673  * and its callers.
1674  */
1675 struct difficulty {
1676     /* Maximum levels allowed.  */
1677     int maxdiff, maxkdiff;
1678     /* Levels reached by the solver.  */
1679     int diff, kdiff;
1680 };
1681
1682 static void solver(int cr, struct block_structure *blocks,
1683                   struct block_structure *kblocks, int xtype,
1684                   digit *grid, digit *kgrid, struct difficulty *dlev)
1685 {
1686     struct solver_usage *usage;
1687     struct solver_scratch *scratch;
1688     int x, y, b, i, n, ret;
1689     int diff = DIFF_BLOCK;
1690     int kdiff = DIFF_KSINGLE;
1691
1692     /*
1693      * Set up a usage structure as a clean slate (everything
1694      * possible).
1695      */
1696     usage = snew(struct solver_usage);
1697     usage->cr = cr;
1698     usage->blocks = blocks;
1699     if (kblocks) {
1700         usage->kblocks = dup_block_structure(kblocks);
1701         usage->extra_cages = alloc_block_structure (kblocks->c, kblocks->r,
1702                                                     cr * cr, cr, cr * cr);
1703         usage->extra_clues = snewn(cr*cr, digit);
1704     } else {
1705         usage->kblocks = usage->extra_cages = NULL;
1706         usage->extra_clues = NULL;
1707     }
1708     usage->cube = snewn(cr*cr*cr, unsigned char);
1709     usage->grid = grid;                /* write straight back to the input */
1710     if (kgrid) {
1711         int nclues;
1712
1713         assert(kblocks);
1714         nclues = kblocks->nr_blocks;
1715         /*
1716          * Allow for expansion of the killer regions, the absolute
1717          * limit is obviously one region per square.
1718          */
1719         usage->kclues = snewn(cr*cr, digit);
1720         for (i = 0; i < nclues; i++) {
1721             for (n = 0; n < kblocks->nr_squares[i]; n++)
1722                 if (kgrid[kblocks->blocks[i][n]] != 0)
1723                     usage->kclues[i] = kgrid[kblocks->blocks[i][n]];
1724             assert(usage->kclues[i] > 0);
1725         }
1726         memset(usage->kclues + nclues, 0, cr*cr - nclues);
1727     } else {
1728         usage->kclues = NULL;
1729     }
1730
1731     memset(usage->cube, TRUE, cr*cr*cr);
1732
1733     usage->row = snewn(cr * cr, unsigned char);
1734     usage->col = snewn(cr * cr, unsigned char);
1735     usage->blk = snewn(cr * cr, unsigned char);
1736     memset(usage->row, FALSE, cr * cr);
1737     memset(usage->col, FALSE, cr * cr);
1738     memset(usage->blk, FALSE, cr * cr);
1739
1740     if (xtype) {
1741         usage->diag = snewn(cr * 2, unsigned char);
1742         memset(usage->diag, FALSE, cr * 2);
1743     } else
1744         usage->diag = NULL; 
1745
1746     usage->nr_regions = cr * 3 + (xtype ? 2 : 0);
1747     usage->regions = snewn(cr * usage->nr_regions, int);
1748     usage->sq2region = snewn(cr * cr * 3, int *);
1749
1750     for (n = 0; n < cr; n++) {
1751         for (i = 0; i < cr; i++) {
1752             x = n*cr+i;
1753             y = i*cr+n;
1754             b = usage->blocks->blocks[n][i];
1755             usage->regions[cr*n*3 + i] = x;
1756             usage->regions[cr*n*3 + cr + i] = y;
1757             usage->regions[cr*n*3 + 2*cr + i] = b;
1758             usage->sq2region[x*3] = usage->regions + cr*n*3;
1759             usage->sq2region[y*3 + 1] = usage->regions + cr*n*3 + cr;
1760             usage->sq2region[b*3 + 2] = usage->regions + cr*n*3 + 2*cr;
1761         }
1762     }
1763
1764     scratch = solver_new_scratch(usage);
1765
1766     /*
1767      * Place all the clue numbers we are given.
1768      */
1769     for (x = 0; x < cr; x++)
1770         for (y = 0; y < cr; y++) {
1771             int n = grid[y*cr+x];
1772             if (n) {
1773                 if (!cube(x,y,n)) {
1774                     diff = DIFF_IMPOSSIBLE;
1775                     goto got_result;
1776                 }
1777                 solver_place(usage, x, y, grid[y*cr+x]);
1778             }
1779         }
1780
1781     /*
1782      * Now loop over the grid repeatedly trying all permitted modes
1783      * of reasoning. The loop terminates if we complete an
1784      * iteration without making any progress; we then return
1785      * failure or success depending on whether the grid is full or
1786      * not.
1787      */
1788     while (1) {
1789         /*
1790          * I'd like to write `continue;' inside each of the
1791          * following loops, so that the solver returns here after
1792          * making some progress. However, I can't specify that I
1793          * want to continue an outer loop rather than the innermost
1794          * one, so I'm apologetically resorting to a goto.
1795          */
1796         cont:
1797
1798         /*
1799          * Blockwise positional elimination.
1800          */
1801         for (b = 0; b < cr; b++)
1802             for (n = 1; n <= cr; n++)
1803                 if (!usage->blk[b*cr+n-1]) {
1804                     for (i = 0; i < cr; i++)
1805                         scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1806                     ret = solver_elim(usage, scratch->indexlist
1807 #ifdef STANDALONE_SOLVER
1808                                       , "positional elimination,"
1809                                       " %d in block %s", n,
1810                                       usage->blocks->blocknames[b]
1811 #endif
1812                                       );
1813                     if (ret < 0) {
1814                         diff = DIFF_IMPOSSIBLE;
1815                         goto got_result;
1816                     } else if (ret > 0) {
1817                         diff = max(diff, DIFF_BLOCK);
1818                         goto cont;
1819                     }
1820                 }
1821
1822         if (usage->kclues != NULL) {
1823             int changed = FALSE;
1824
1825             /*
1826              * First, bring the kblocks into a more useful form: remove
1827              * all filled-in squares, and reduce the sum by their values.
1828              * Walk in reverse order, since otherwise remove_from_block
1829              * can move element past our loop counter.
1830              */
1831             for (b = 0; b < usage->kblocks->nr_blocks; b++)
1832                 for (i = usage->kblocks->nr_squares[b] -1; i >= 0; i--) {
1833                     int x = usage->kblocks->blocks[b][i];
1834                     int t = usage->grid[x];
1835
1836                     if (t == 0)
1837                         continue;
1838                     remove_from_block(usage->kblocks, b, x);
1839                     if (t > usage->kclues[b]) {
1840                         diff = DIFF_IMPOSSIBLE;
1841                         goto got_result;
1842                     }
1843                     usage->kclues[b] -= t;
1844                     /*
1845                      * Since cages are regions, this tells us something
1846                      * about the other squares in the cage.
1847                      */
1848                     for (n = 0; n < usage->kblocks->nr_squares[b]; n++) {
1849                         cube2(usage->kblocks->blocks[b][n], t) = FALSE;
1850                     }
1851                 }
1852
1853             /*
1854              * The most trivial kind of solver for killer puzzles: fill
1855              * single-square cages.
1856              */
1857             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1858                 int squares = usage->kblocks->nr_squares[b];
1859                 if (squares == 1) {
1860                     int v = usage->kclues[b];
1861                     if (v < 1 || v > cr) {
1862                         diff = DIFF_IMPOSSIBLE;
1863                         goto got_result;
1864                     }
1865                     x = usage->kblocks->blocks[b][0] % cr;
1866                     y = usage->kblocks->blocks[b][0] / cr;
1867                     if (!cube(x, y, v)) {
1868                         diff = DIFF_IMPOSSIBLE;
1869                         goto got_result;
1870                     }
1871                     solver_place(usage, x, y, v);
1872
1873 #ifdef STANDALONE_SOLVER
1874                     if (solver_show_working) {
1875                         printf("%*s  placing %d at (%d,%d)\n",
1876                                solver_recurse_depth*4, "killer single-square cage",
1877                                v, 1 + x%cr, 1 + x/cr);
1878                     }
1879 #endif
1880                     changed = TRUE;
1881                 }
1882             }
1883
1884             if (changed) {
1885                 kdiff = max(kdiff, DIFF_KSINGLE);
1886                 goto cont;
1887             }
1888         }
1889         if (dlev->maxkdiff >= DIFF_KINTERSECT && usage->kclues != NULL) {
1890             int changed = FALSE;
1891             /*
1892              * Now, create the extra_cages information.  Every full region
1893              * (row, column, or block) has the same sum total (45 for 3x3
1894              * puzzles.  After we try to cover these regions with cages that
1895              * lie entirely within them, any squares that remain must bring
1896              * the total to this known value, and so they form additional
1897              * cages which aren't immediately evident in the displayed form
1898              * of the puzzle.
1899              */
1900             usage->extra_cages->nr_blocks = 0;
1901             for (i = 0; i < 3; i++) {
1902                 for (n = 0; n < cr; n++) {
1903                     int *region = usage->regions + cr*n*3 + i*cr;
1904                     int sum = cr * (cr + 1) / 2;
1905                     int nsquares = cr;
1906                     int filtered;
1907                     int n_extra = usage->extra_cages->nr_blocks;
1908                     int *extra_list = usage->extra_cages->blocks[n_extra];
1909                     memcpy(extra_list, region, cr * sizeof *extra_list);
1910
1911                     nsquares = filter_whole_cages(usage, extra_list, nsquares, &filtered);
1912                     sum -= filtered;
1913                     if (nsquares == cr || nsquares == 0)
1914                         continue;
1915                     if (dlev->maxdiff >= DIFF_RECURSIVE) {
1916                         if (sum <= 0) {
1917                             dlev->diff = DIFF_IMPOSSIBLE;
1918                             goto got_result;
1919                         }
1920                     }
1921                     assert(sum > 0);
1922
1923                     if (nsquares == 1) {
1924                         if (sum > cr) {
1925                             diff = DIFF_IMPOSSIBLE;
1926                             goto got_result;
1927                         }
1928                         x = extra_list[0] % cr;
1929                         y = extra_list[0] / cr;
1930                         if (!cube(x, y, sum)) {
1931                             diff = DIFF_IMPOSSIBLE;
1932                             goto got_result;
1933                         }
1934                         solver_place(usage, x, y, sum);
1935                         changed = TRUE;
1936 #ifdef STANDALONE_SOLVER
1937                         if (solver_show_working) {
1938                             printf("%*s  placing %d at (%d,%d)\n",
1939                                    solver_recurse_depth*4, "killer single-square deduced cage",
1940                                    sum, 1 + x, 1 + y);
1941                         }
1942 #endif
1943                     }
1944
1945                     b = usage->kblocks->whichblock[extra_list[0]];
1946                     for (x = 1; x < nsquares; x++)
1947                         if (usage->kblocks->whichblock[extra_list[x]] != b)
1948                             break;
1949                     if (x == nsquares) {
1950                         assert(usage->kblocks->nr_squares[b] > nsquares);
1951                         split_block(usage->kblocks, extra_list, nsquares);
1952                         assert(usage->kblocks->nr_squares[usage->kblocks->nr_blocks - 1] == nsquares);
1953                         usage->kclues[usage->kblocks->nr_blocks - 1] = sum;
1954                         usage->kclues[b] -= sum;
1955                     } else {
1956                         usage->extra_cages->nr_squares[n_extra] = nsquares;
1957                         usage->extra_cages->nr_blocks++;
1958                         usage->extra_clues[n_extra] = sum;
1959                     }
1960                 }
1961             }
1962             if (changed) {
1963                 kdiff = max(kdiff, DIFF_KINTERSECT);
1964                 goto cont;
1965             }
1966         }
1967
1968         /*
1969          * Another simple killer-type elimination.  For every square in a
1970          * cage, find the minimum and maximum possible sums of all the
1971          * other squares in the same cage, and rule out possibilities
1972          * for the given square based on whether they are guaranteed to
1973          * cause the sum to be either too high or too low.
1974          * This is a special case of trying all possible sums across a
1975          * region, which is a recursive algorithm.  We should probably
1976          * implement it for a higher difficulty level.
1977          */
1978         if (dlev->maxkdiff >= DIFF_KMINMAX && usage->kclues != NULL) {
1979             int changed = FALSE;
1980             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1981                 int ret = solver_killer_minmax(usage, usage->kblocks,
1982                                                usage->kclues, b
1983 #ifdef STANDALONE_SOLVER
1984                                              , ""
1985 #endif
1986                                                );
1987                 if (ret < 0) {
1988                     diff = DIFF_IMPOSSIBLE;
1989                     goto got_result;
1990                 } else if (ret > 0)
1991                     changed = TRUE;
1992             }
1993             for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
1994                 int ret = solver_killer_minmax(usage, usage->extra_cages,
1995                                                usage->extra_clues, b
1996 #ifdef STANDALONE_SOLVER
1997                                                , "using deduced cages"
1998 #endif
1999                                                );
2000                 if (ret < 0) {
2001                     diff = DIFF_IMPOSSIBLE;
2002                     goto got_result;
2003                 } else if (ret > 0)
2004                     changed = TRUE;
2005             }
2006             if (changed) {
2007                 kdiff = max(kdiff, DIFF_KMINMAX);
2008                 goto cont;
2009             }
2010         }
2011
2012         /*
2013          * Try to use knowledge of which numbers can be used to generate
2014          * a given sum.
2015          * This can only be used if a cage lies entirely within a region.
2016          */
2017         if (dlev->maxkdiff >= DIFF_KSUMS && usage->kclues != NULL) {
2018             int changed = FALSE;
2019
2020             for (b = 0; b < usage->kblocks->nr_blocks; b++) {
2021                 int ret = solver_killer_sums(usage, b, usage->kblocks,
2022                                              usage->kclues[b], TRUE
2023 #ifdef STANDALONE_SOLVER
2024                                              , "regular clues"
2025 #endif
2026                                              );
2027                 if (ret > 0) {
2028                     changed = TRUE;
2029                     kdiff = max(kdiff, DIFF_KSUMS);
2030                 } else if (ret < 0) {
2031                     diff = DIFF_IMPOSSIBLE;
2032                     goto got_result;
2033                 }
2034             }
2035
2036             for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
2037                 int ret = solver_killer_sums(usage, b, usage->extra_cages,
2038                                              usage->extra_clues[b], FALSE
2039 #ifdef STANDALONE_SOLVER
2040                                              , "deduced clues"
2041 #endif
2042                                              );
2043                 if (ret > 0) {
2044                     changed = TRUE;
2045                     kdiff = max(kdiff, DIFF_KSUMS);
2046                 } else if (ret < 0) {
2047                     diff = DIFF_IMPOSSIBLE;
2048                     goto got_result;
2049                 }
2050             }
2051
2052             if (changed)
2053                 goto cont;
2054         }
2055
2056         if (dlev->maxdiff <= DIFF_BLOCK)
2057             break;
2058
2059         /*
2060          * Row-wise positional elimination.
2061          */
2062         for (y = 0; y < cr; y++)
2063             for (n = 1; n <= cr; n++)
2064                 if (!usage->row[y*cr+n-1]) {
2065                     for (x = 0; x < cr; x++)
2066                         scratch->indexlist[x] = cubepos(x, y, n);
2067                     ret = solver_elim(usage, scratch->indexlist
2068 #ifdef STANDALONE_SOLVER
2069                                       , "positional elimination,"
2070                                       " %d in row %d", n, 1+y
2071 #endif
2072                                       );
2073                     if (ret < 0) {
2074                         diff = DIFF_IMPOSSIBLE;
2075                         goto got_result;
2076                     } else if (ret > 0) {
2077                         diff = max(diff, DIFF_SIMPLE);
2078                         goto cont;
2079                     }
2080                 }
2081         /*
2082          * Column-wise positional elimination.
2083          */
2084         for (x = 0; x < cr; x++)
2085             for (n = 1; n <= cr; n++)
2086                 if (!usage->col[x*cr+n-1]) {
2087                     for (y = 0; y < cr; y++)
2088                         scratch->indexlist[y] = cubepos(x, y, n);
2089                     ret = solver_elim(usage, scratch->indexlist
2090 #ifdef STANDALONE_SOLVER
2091                                       , "positional elimination,"
2092                                       " %d in column %d", n, 1+x
2093 #endif
2094                                       );
2095                     if (ret < 0) {
2096                         diff = DIFF_IMPOSSIBLE;
2097                         goto got_result;
2098                     } else if (ret > 0) {
2099                         diff = max(diff, DIFF_SIMPLE);
2100                         goto cont;
2101                     }
2102                 }
2103
2104         /*
2105          * X-diagonal positional elimination.
2106          */
2107         if (usage->diag) {
2108             for (n = 1; n <= cr; n++)
2109                 if (!usage->diag[n-1]) {
2110                     for (i = 0; i < cr; i++)
2111                         scratch->indexlist[i] = cubepos2(diag0(i), n);
2112                     ret = solver_elim(usage, scratch->indexlist
2113 #ifdef STANDALONE_SOLVER
2114                                       , "positional elimination,"
2115                                       " %d in \\-diagonal", n
2116 #endif
2117                                       );
2118                     if (ret < 0) {
2119                         diff = DIFF_IMPOSSIBLE;
2120                         goto got_result;
2121                     } else if (ret > 0) {
2122                         diff = max(diff, DIFF_SIMPLE);
2123                         goto cont;
2124                     }
2125                 }
2126             for (n = 1; n <= cr; n++)
2127                 if (!usage->diag[cr+n-1]) {
2128                     for (i = 0; i < cr; i++)
2129                         scratch->indexlist[i] = cubepos2(diag1(i), n);
2130                     ret = solver_elim(usage, scratch->indexlist
2131 #ifdef STANDALONE_SOLVER
2132                                       , "positional elimination,"
2133                                       " %d in /-diagonal", n
2134 #endif
2135                                       );
2136                     if (ret < 0) {
2137                         diff = DIFF_IMPOSSIBLE;
2138                         goto got_result;
2139                     } else if (ret > 0) {
2140                         diff = max(diff, DIFF_SIMPLE);
2141                         goto cont;
2142                     }
2143                 }
2144         }
2145
2146         /*
2147          * Numeric elimination.
2148          */
2149         for (x = 0; x < cr; x++)
2150             for (y = 0; y < cr; y++)
2151                 if (!usage->grid[y*cr+x]) {
2152                     for (n = 1; n <= cr; n++)
2153                         scratch->indexlist[n-1] = cubepos(x, y, n);
2154                     ret = solver_elim(usage, scratch->indexlist
2155 #ifdef STANDALONE_SOLVER
2156                                       , "numeric elimination at (%d,%d)",
2157                                       1+x, 1+y
2158 #endif
2159                                       );
2160                     if (ret < 0) {
2161                         diff = DIFF_IMPOSSIBLE;
2162                         goto got_result;
2163                     } else if (ret > 0) {
2164                         diff = max(diff, DIFF_SIMPLE);
2165                         goto cont;
2166                     }
2167                 }
2168
2169         if (dlev->maxdiff <= DIFF_SIMPLE)
2170             break;
2171
2172         /*
2173          * Intersectional analysis, rows vs blocks.
2174          */
2175         for (y = 0; y < cr; y++)
2176             for (b = 0; b < cr; b++)
2177                 for (n = 1; n <= cr; n++) {
2178                     if (usage->row[y*cr+n-1] ||
2179                         usage->blk[b*cr+n-1])
2180                         continue;
2181                     for (i = 0; i < cr; i++) {
2182                         scratch->indexlist[i] = cubepos(i, y, n);
2183                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2184                     }
2185                     /*
2186                      * solver_intersect() never returns -1.
2187                      */
2188                     if (solver_intersect(usage, scratch->indexlist,
2189                                          scratch->indexlist2
2190 #ifdef STANDALONE_SOLVER
2191                                           , "intersectional analysis,"
2192                                           " %d in row %d vs block %s",
2193                                           n, 1+y, usage->blocks->blocknames[b]
2194 #endif
2195                                           ) ||
2196                          solver_intersect(usage, scratch->indexlist2,
2197                                          scratch->indexlist
2198 #ifdef STANDALONE_SOLVER
2199                                           , "intersectional analysis,"
2200                                           " %d in block %s vs row %d",
2201                                           n, usage->blocks->blocknames[b], 1+y
2202 #endif
2203                                           )) {
2204                         diff = max(diff, DIFF_INTERSECT);
2205                         goto cont;
2206                     }
2207                 }
2208
2209         /*
2210          * Intersectional analysis, columns vs blocks.
2211          */
2212         for (x = 0; x < cr; x++)
2213             for (b = 0; b < cr; b++)
2214                 for (n = 1; n <= cr; n++) {
2215                     if (usage->col[x*cr+n-1] ||
2216                         usage->blk[b*cr+n-1])
2217                         continue;
2218                     for (i = 0; i < cr; i++) {
2219                         scratch->indexlist[i] = cubepos(x, i, n);
2220                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2221                     }
2222                     if (solver_intersect(usage, scratch->indexlist,
2223                                          scratch->indexlist2
2224 #ifdef STANDALONE_SOLVER
2225                                           , "intersectional analysis,"
2226                                           " %d in column %d vs block %s",
2227                                           n, 1+x, usage->blocks->blocknames[b]
2228 #endif
2229                                           ) ||
2230                          solver_intersect(usage, scratch->indexlist2,
2231                                          scratch->indexlist
2232 #ifdef STANDALONE_SOLVER
2233                                           , "intersectional analysis,"
2234                                           " %d in block %s vs column %d",
2235                                           n, usage->blocks->blocknames[b], 1+x
2236 #endif
2237                                           )) {
2238                         diff = max(diff, DIFF_INTERSECT);
2239                         goto cont;
2240                     }
2241                 }
2242
2243         if (usage->diag) {
2244             /*
2245              * Intersectional analysis, \-diagonal vs blocks.
2246              */
2247             for (b = 0; b < cr; b++)
2248                 for (n = 1; n <= cr; n++) {
2249                     if (usage->diag[n-1] ||
2250                         usage->blk[b*cr+n-1])
2251                         continue;
2252                     for (i = 0; i < cr; i++) {
2253                         scratch->indexlist[i] = cubepos2(diag0(i), n);
2254                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2255                     }
2256                     if (solver_intersect(usage, scratch->indexlist,
2257                                          scratch->indexlist2
2258 #ifdef STANDALONE_SOLVER
2259                                           , "intersectional analysis,"
2260                                           " %d in \\-diagonal vs block %s",
2261                                           n, usage->blocks->blocknames[b]
2262 #endif
2263                                           ) ||
2264                          solver_intersect(usage, scratch->indexlist2,
2265                                          scratch->indexlist
2266 #ifdef STANDALONE_SOLVER
2267                                           , "intersectional analysis,"
2268                                           " %d in block %s vs \\-diagonal",
2269                                           n, usage->blocks->blocknames[b]
2270 #endif
2271                                           )) {
2272                         diff = max(diff, DIFF_INTERSECT);
2273                         goto cont;
2274                     }
2275                 }
2276
2277             /*
2278              * Intersectional analysis, /-diagonal vs blocks.
2279              */
2280             for (b = 0; b < cr; b++)
2281                 for (n = 1; n <= cr; n++) {
2282                     if (usage->diag[cr+n-1] ||
2283                         usage->blk[b*cr+n-1])
2284                         continue;
2285                     for (i = 0; i < cr; i++) {
2286                         scratch->indexlist[i] = cubepos2(diag1(i), n);
2287                         scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2288                     }
2289                     if (solver_intersect(usage, scratch->indexlist,
2290                                          scratch->indexlist2
2291 #ifdef STANDALONE_SOLVER
2292                                           , "intersectional analysis,"
2293                                           " %d in /-diagonal vs block %s",
2294                                           n, usage->blocks->blocknames[b]
2295 #endif
2296                                           ) ||
2297                          solver_intersect(usage, scratch->indexlist2,
2298                                          scratch->indexlist
2299 #ifdef STANDALONE_SOLVER
2300                                           , "intersectional analysis,"
2301                                           " %d in block %s vs /-diagonal",
2302                                           n, usage->blocks->blocknames[b]
2303 #endif
2304                                           )) {
2305                         diff = max(diff, DIFF_INTERSECT);
2306                         goto cont;
2307                     }
2308                 }
2309         }
2310
2311         if (dlev->maxdiff <= DIFF_INTERSECT)
2312             break;
2313
2314         /*
2315          * Blockwise set elimination.
2316          */
2317         for (b = 0; b < cr; b++) {
2318             for (i = 0; i < cr; i++)
2319                 for (n = 1; n <= cr; n++)
2320                     scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
2321             ret = solver_set(usage, scratch, scratch->indexlist
2322 #ifdef STANDALONE_SOLVER
2323                              , "set elimination, block %s",
2324                              usage->blocks->blocknames[b]
2325 #endif
2326                                  );
2327             if (ret < 0) {
2328                 diff = DIFF_IMPOSSIBLE;
2329                 goto got_result;
2330             } else if (ret > 0) {
2331                 diff = max(diff, DIFF_SET);
2332                 goto cont;
2333             }
2334         }
2335
2336         /*
2337          * Row-wise set elimination.
2338          */
2339         for (y = 0; y < cr; y++) {
2340             for (x = 0; x < cr; x++)
2341                 for (n = 1; n <= cr; n++)
2342                     scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
2343             ret = solver_set(usage, scratch, scratch->indexlist
2344 #ifdef STANDALONE_SOLVER
2345                              , "set elimination, row %d", 1+y
2346 #endif
2347                              );
2348             if (ret < 0) {
2349                 diff = DIFF_IMPOSSIBLE;
2350                 goto got_result;
2351             } else if (ret > 0) {
2352                 diff = max(diff, DIFF_SET);
2353                 goto cont;
2354             }
2355         }
2356
2357         /*
2358          * Column-wise set elimination.
2359          */
2360         for (x = 0; x < cr; x++) {
2361             for (y = 0; y < cr; y++)
2362                 for (n = 1; n <= cr; n++)
2363                     scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
2364             ret = solver_set(usage, scratch, scratch->indexlist
2365 #ifdef STANDALONE_SOLVER
2366                              , "set elimination, column %d", 1+x
2367 #endif
2368                              );
2369             if (ret < 0) {
2370                 diff = DIFF_IMPOSSIBLE;
2371                 goto got_result;
2372             } else if (ret > 0) {
2373                 diff = max(diff, DIFF_SET);
2374                 goto cont;
2375             }
2376         }
2377
2378         if (usage->diag) {
2379             /*
2380              * \-diagonal set elimination.
2381              */
2382             for (i = 0; i < cr; i++)
2383                 for (n = 1; n <= cr; n++)
2384                     scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
2385             ret = solver_set(usage, scratch, scratch->indexlist
2386 #ifdef STANDALONE_SOLVER
2387                              , "set elimination, \\-diagonal"
2388 #endif
2389                              );
2390             if (ret < 0) {
2391                 diff = DIFF_IMPOSSIBLE;
2392                 goto got_result;
2393             } else if (ret > 0) {
2394                 diff = max(diff, DIFF_SET);
2395                 goto cont;
2396             }
2397
2398             /*
2399              * /-diagonal set elimination.
2400              */
2401             for (i = 0; i < cr; i++)
2402                 for (n = 1; n <= cr; n++)
2403                     scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
2404             ret = solver_set(usage, scratch, scratch->indexlist
2405 #ifdef STANDALONE_SOLVER
2406                              , "set elimination, /-diagonal"
2407 #endif
2408                              );
2409             if (ret < 0) {
2410                 diff = DIFF_IMPOSSIBLE;
2411                 goto got_result;
2412             } else if (ret > 0) {
2413                 diff = max(diff, DIFF_SET);
2414                 goto cont;
2415             }
2416         }
2417
2418         if (dlev->maxdiff <= DIFF_SET)
2419             break;
2420
2421         /*
2422          * Row-vs-column set elimination on a single number.
2423          */
2424         for (n = 1; n <= cr; n++) {
2425             for (y = 0; y < cr; y++)
2426                 for (x = 0; x < cr; x++)
2427                     scratch->indexlist[y*cr+x] = cubepos(x, y, n);
2428             ret = solver_set(usage, scratch, scratch->indexlist
2429 #ifdef STANDALONE_SOLVER
2430                              , "positional set elimination, number %d", n
2431 #endif
2432                              );
2433             if (ret < 0) {
2434                 diff = DIFF_IMPOSSIBLE;
2435                 goto got_result;
2436             } else if (ret > 0) {
2437                 diff = max(diff, DIFF_EXTREME);
2438                 goto cont;
2439             }
2440         }
2441
2442         /*
2443          * Forcing chains.
2444          */
2445         if (solver_forcing(usage, scratch)) {
2446             diff = max(diff, DIFF_EXTREME);
2447             goto cont;
2448         }
2449
2450         /*
2451          * If we reach here, we have made no deductions in this
2452          * iteration, so the algorithm terminates.
2453          */
2454         break;
2455     }
2456
2457     /*
2458      * Last chance: if we haven't fully solved the puzzle yet, try
2459      * recursing based on guesses for a particular square. We pick
2460      * one of the most constrained empty squares we can find, which
2461      * has the effect of pruning the search tree as much as
2462      * possible.
2463      */
2464     if (dlev->maxdiff >= DIFF_RECURSIVE) {
2465         int best, bestcount;
2466
2467         best = -1;
2468         bestcount = cr+1;
2469
2470         for (y = 0; y < cr; y++)
2471             for (x = 0; x < cr; x++)
2472                 if (!grid[y*cr+x]) {
2473                     int count;
2474
2475                     /*
2476                      * An unfilled square. Count the number of
2477                      * possible digits in it.
2478                      */
2479                     count = 0;
2480                     for (n = 1; n <= cr; n++)
2481                         if (cube(x,y,n))
2482                             count++;
2483
2484                     /*
2485                      * We should have found any impossibilities
2486                      * already, so this can safely be an assert.
2487                      */
2488                     assert(count > 1);
2489
2490                     if (count < bestcount) {
2491                         bestcount = count;
2492                         best = y*cr+x;
2493                     }
2494                 }
2495
2496         if (best != -1) {
2497             int i, j;
2498             digit *list, *ingrid, *outgrid;
2499
2500             diff = DIFF_IMPOSSIBLE;    /* no solution found yet */
2501
2502             /*
2503              * Attempt recursion.
2504              */
2505             y = best / cr;
2506             x = best % cr;
2507
2508             list = snewn(cr, digit);
2509             ingrid = snewn(cr * cr, digit);
2510             outgrid = snewn(cr * cr, digit);
2511             memcpy(ingrid, grid, cr * cr);
2512
2513             /* Make a list of the possible digits. */
2514             for (j = 0, n = 1; n <= cr; n++)
2515                 if (cube(x,y,n))
2516                     list[j++] = n;
2517
2518 #ifdef STANDALONE_SOLVER
2519             if (solver_show_working) {
2520                 const char *sep = "";
2521                 printf("%*srecursing on (%d,%d) [",
2522                        solver_recurse_depth*4, "", x + 1, y + 1);
2523                 for (i = 0; i < j; i++) {
2524                     printf("%s%d", sep, list[i]);
2525                     sep = " or ";
2526                 }
2527                 printf("]\n");
2528             }
2529 #endif
2530
2531             /*
2532              * And step along the list, recursing back into the
2533              * main solver at every stage.
2534              */
2535             for (i = 0; i < j; i++) {
2536                 memcpy(outgrid, ingrid, cr * cr);
2537                 outgrid[y*cr+x] = list[i];
2538
2539 #ifdef STANDALONE_SOLVER
2540                 if (solver_show_working)
2541                     printf("%*sguessing %d at (%d,%d)\n",
2542                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2543                 solver_recurse_depth++;
2544 #endif
2545
2546                 solver(cr, blocks, kblocks, xtype, outgrid, kgrid, dlev);
2547
2548 #ifdef STANDALONE_SOLVER
2549                 solver_recurse_depth--;
2550                 if (solver_show_working) {
2551                     printf("%*sretracting %d at (%d,%d)\n",
2552                            solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2553                 }
2554 #endif
2555
2556                 /*
2557                  * If we have our first solution, copy it into the
2558                  * grid we will return.
2559                  */
2560                 if (diff == DIFF_IMPOSSIBLE && dlev->diff != DIFF_IMPOSSIBLE)
2561                     memcpy(grid, outgrid, cr*cr);
2562
2563                 if (dlev->diff == DIFF_AMBIGUOUS)
2564                     diff = DIFF_AMBIGUOUS;
2565                 else if (dlev->diff == DIFF_IMPOSSIBLE)
2566                     /* do not change our return value */;
2567                 else {
2568                     /* the recursion turned up exactly one solution */
2569                     if (diff == DIFF_IMPOSSIBLE)
2570                         diff = DIFF_RECURSIVE;
2571                     else
2572                         diff = DIFF_AMBIGUOUS;
2573                 }
2574
2575                 /*
2576                  * As soon as we've found more than one solution,
2577                  * give up immediately.
2578                  */
2579                 if (diff == DIFF_AMBIGUOUS)
2580                     break;
2581             }
2582
2583             sfree(outgrid);
2584             sfree(ingrid);
2585             sfree(list);
2586         }
2587
2588     } else {
2589         /*
2590          * We're forbidden to use recursion, so we just see whether
2591          * our grid is fully solved, and return DIFF_IMPOSSIBLE
2592          * otherwise.
2593          */
2594         for (y = 0; y < cr; y++)
2595             for (x = 0; x < cr; x++)
2596                 if (!grid[y*cr+x])
2597                     diff = DIFF_IMPOSSIBLE;
2598     }
2599
2600     got_result:
2601     dlev->diff = diff;
2602     dlev->kdiff = kdiff;
2603
2604 #ifdef STANDALONE_SOLVER
2605     if (solver_show_working)
2606         printf("%*s%s found\n",
2607                solver_recurse_depth*4, "",
2608                diff == DIFF_IMPOSSIBLE ? "no solution" :
2609                diff == DIFF_AMBIGUOUS ? "multiple solutions" :
2610                "one solution");
2611 #endif
2612
2613     sfree(usage->sq2region);
2614     sfree(usage->regions);
2615     sfree(usage->cube);
2616     sfree(usage->row);
2617     sfree(usage->col);
2618     sfree(usage->blk);
2619     if (usage->kblocks) {
2620         free_block_structure(usage->kblocks);
2621         free_block_structure(usage->extra_cages);
2622         sfree(usage->extra_clues);
2623     }
2624     if (usage->kclues) sfree(usage->kclues);
2625     sfree(usage);
2626
2627     solver_free_scratch(scratch);
2628 }
2629
2630 /* ----------------------------------------------------------------------
2631  * End of solver code.
2632  */
2633
2634 /* ----------------------------------------------------------------------
2635  * Killer set generator.
2636  */
2637
2638 /* ----------------------------------------------------------------------
2639  * Solo filled-grid generator.
2640  *
2641  * This grid generator works by essentially trying to solve a grid
2642  * starting from no clues, and not worrying that there's more than
2643  * one possible solution. Unfortunately, it isn't computationally
2644  * feasible to do this by calling the above solver with an empty
2645  * grid, because that one needs to allocate a lot of scratch space
2646  * at every recursion level. Instead, I have a much simpler
2647  * algorithm which I shamelessly copied from a Python solver
2648  * written by Andrew Wilkinson (which is GPLed, but I've reused
2649  * only ideas and no code). It mostly just does the obvious
2650  * recursive thing: pick an empty square, put one of the possible
2651  * digits in it, recurse until all squares are filled, backtrack
2652  * and change some choices if necessary.
2653  *
2654  * The clever bit is that every time it chooses which square to
2655  * fill in next, it does so by counting the number of _possible_
2656  * numbers that can go in each square, and it prioritises so that
2657  * it picks a square with the _lowest_ number of possibilities. The
2658  * idea is that filling in lots of the obvious bits (particularly
2659  * any squares with only one possibility) will cut down on the list
2660  * of possibilities for other squares and hence reduce the enormous
2661  * search space as much as possible as early as possible.
2662  *
2663  * The use of bit sets implies that we support puzzles up to a size of
2664  * 32x32 (less if anyone finds a 16-bit machine to compile this on).
2665  */
2666
2667 /*
2668  * Internal data structure used in gridgen to keep track of
2669  * progress.
2670  */
2671 struct gridgen_coord { int x, y, r; };
2672 struct gridgen_usage {
2673     int cr;
2674     struct block_structure *blocks, *kblocks;
2675     /* grid is a copy of the input grid, modified as we go along */
2676     digit *grid;
2677     /*
2678      * Bitsets.  In each of them, bit n is set if digit n has been placed
2679      * in the corresponding region.  row, col and blk are used for all
2680      * puzzles.  cge is used only for killer puzzles, and diag is used
2681      * only for x-type puzzles.
2682      * All of these have cr entries, except diag which only has 2,
2683      * and cge, which has as many entries as kblocks.
2684      */
2685     unsigned int *row, *col, *blk, *cge, *diag;
2686     /* This lists all the empty spaces remaining in the grid. */
2687     struct gridgen_coord *spaces;
2688     int nspaces;
2689     /* If we need randomisation in the solve, this is our random state. */
2690     random_state *rs;
2691 };
2692
2693 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n)
2694 {
2695     unsigned int bit = 1 << n;
2696     int cr = usage->cr;
2697     usage->row[y] |= bit;
2698     usage->col[x] |= bit;
2699     usage->blk[usage->blocks->whichblock[y*cr+x]] |= bit;
2700     if (usage->cge)
2701         usage->cge[usage->kblocks->whichblock[y*cr+x]] |= bit;
2702     if (usage->diag) {
2703         if (ondiag0(y*cr+x))
2704             usage->diag[0] |= bit;
2705         if (ondiag1(y*cr+x))
2706             usage->diag[1] |= bit;
2707     }
2708     usage->grid[y*cr+x] = n;
2709 }
2710
2711 static void gridgen_remove(struct gridgen_usage *usage, int x, int y, digit n)
2712 {
2713     unsigned int mask = ~(1 << n);
2714     int cr = usage->cr;
2715     usage->row[y] &= mask;
2716     usage->col[x] &= mask;
2717     usage->blk[usage->blocks->whichblock[y*cr+x]] &= mask;
2718     if (usage->cge)
2719         usage->cge[usage->kblocks->whichblock[y*cr+x]] &= mask;
2720     if (usage->diag) {
2721         if (ondiag0(y*cr+x))
2722             usage->diag[0] &= mask;
2723         if (ondiag1(y*cr+x))
2724             usage->diag[1] &= mask;
2725     }
2726     usage->grid[y*cr+x] = 0;
2727 }
2728
2729 #define N_SINGLE 32
2730
2731 /*
2732  * The real recursive step in the generating function.
2733  *
2734  * Return values: 1 means solution found, 0 means no solution
2735  * found on this branch.
2736  */
2737 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
2738 {
2739     int cr = usage->cr;
2740     int i, j, n, sx, sy, bestm, bestr, ret;
2741     int *digits;
2742     unsigned int used;
2743
2744     /*
2745      * Firstly, check for completion! If there are no spaces left
2746      * in the grid, we have a solution.
2747      */
2748     if (usage->nspaces == 0)
2749         return TRUE;
2750
2751     /*
2752      * Next, abandon generation if we went over our steps limit.
2753      */
2754     if (*steps <= 0)
2755         return FALSE;
2756     (*steps)--;
2757
2758     /*
2759      * Otherwise, there must be at least one space. Find the most
2760      * constrained space, using the `r' field as a tie-breaker.
2761      */
2762     bestm = cr+1;                      /* so that any space will beat it */
2763     bestr = 0;
2764     used = ~0;
2765     i = sx = sy = -1;
2766     for (j = 0; j < usage->nspaces; j++) {
2767         int x = usage->spaces[j].x, y = usage->spaces[j].y;
2768         unsigned int used_xy;
2769         int m;
2770
2771         m = usage->blocks->whichblock[y*cr+x];
2772         used_xy = usage->row[y] | usage->col[x] | usage->blk[m];
2773         if (usage->cge != NULL)
2774             used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2775         if (usage->cge != NULL)
2776             used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2777         if (usage->diag != NULL) {
2778             if (ondiag0(y*cr+x))
2779                 used_xy |= usage->diag[0];
2780             if (ondiag1(y*cr+x))
2781                 used_xy |= usage->diag[1];
2782         }
2783
2784         /*
2785          * Find the number of digits that could go in this space.
2786          */
2787         m = 0;
2788         for (n = 1; n <= cr; n++) {
2789             unsigned int bit = 1 << n;
2790             if ((used_xy & bit) == 0)
2791                 m++;
2792         }
2793         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
2794             bestm = m;
2795             bestr = usage->spaces[j].r;
2796             sx = x;
2797             sy = y;
2798             i = j;
2799             used = used_xy;
2800         }
2801     }
2802
2803     /*
2804      * Swap that square into the final place in the spaces array,
2805      * so that decrementing nspaces will remove it from the list.
2806      */
2807     if (i != usage->nspaces-1) {
2808         struct gridgen_coord t;
2809         t = usage->spaces[usage->nspaces-1];
2810         usage->spaces[usage->nspaces-1] = usage->spaces[i];
2811         usage->spaces[i] = t;
2812     }
2813
2814     /*
2815      * Now we've decided which square to start our recursion at,
2816      * simply go through all possible values, shuffling them
2817      * randomly first if necessary.
2818      */
2819     digits = snewn(bestm, int);
2820
2821     j = 0;
2822     for (n = 1; n <= cr; n++) {
2823         unsigned int bit = 1 << n;
2824
2825         if ((used & bit) == 0)
2826             digits[j++] = n;
2827     }
2828
2829     if (usage->rs)
2830         shuffle(digits, j, sizeof(*digits), usage->rs);
2831
2832     /* And finally, go through the digit list and actually recurse. */
2833     ret = FALSE;
2834     for (i = 0; i < j; i++) {
2835         n = digits[i];
2836
2837         /* Update the usage structure to reflect the placing of this digit. */
2838         gridgen_place(usage, sx, sy, n);
2839         usage->nspaces--;
2840
2841         /* Call the solver recursively. Stop when we find a solution. */
2842         if (gridgen_real(usage, grid, steps)) {
2843             ret = TRUE;
2844             break;
2845         }
2846
2847         /* Revert the usage structure. */
2848         gridgen_remove(usage, sx, sy, n);
2849         usage->nspaces++;
2850     }
2851
2852     sfree(digits);
2853     return ret;
2854 }
2855
2856 /*
2857  * Entry point to generator. You give it parameters and a starting
2858  * grid, which is simply an array of cr*cr digits.
2859  */
2860 static int gridgen(int cr, struct block_structure *blocks,
2861                    struct block_structure *kblocks, int xtype,
2862                    digit *grid, random_state *rs, int maxsteps)
2863 {
2864     struct gridgen_usage *usage;
2865     int x, y, ret;
2866
2867     /*
2868      * Clear the grid to start with.
2869      */
2870     memset(grid, 0, cr*cr);
2871
2872     /*
2873      * Create a gridgen_usage structure.
2874      */
2875     usage = snew(struct gridgen_usage);
2876
2877     usage->cr = cr;
2878     usage->blocks = blocks;
2879
2880     usage->grid = grid;
2881
2882     usage->row = snewn(cr, unsigned int);
2883     usage->col = snewn(cr, unsigned int);
2884     usage->blk = snewn(cr, unsigned int);
2885     if (kblocks != NULL) {
2886         usage->kblocks = kblocks;
2887         usage->cge = snewn(usage->kblocks->nr_blocks, unsigned int);
2888         memset(usage->cge, FALSE, kblocks->nr_blocks * sizeof *usage->cge);
2889     } else {
2890         usage->cge = NULL;
2891     }
2892
2893     memset(usage->row, 0, cr * sizeof *usage->row);
2894     memset(usage->col, 0, cr * sizeof *usage->col);
2895     memset(usage->blk, 0, cr * sizeof *usage->blk);
2896
2897     if (xtype) {
2898         usage->diag = snewn(2, unsigned int);
2899         memset(usage->diag, 0, 2 * sizeof *usage->diag);
2900     } else {
2901         usage->diag = NULL;
2902     }
2903
2904     /*
2905      * Begin by filling in the whole top row with randomly chosen
2906      * numbers. This cannot introduce any bias or restriction on
2907      * the available grids, since we already know those numbers
2908      * are all distinct so all we're doing is choosing their
2909      * labels.
2910      */
2911     for (x = 0; x < cr; x++)
2912         grid[x] = x+1;
2913     shuffle(grid, cr, sizeof(*grid), rs);
2914     for (x = 0; x < cr; x++)
2915         gridgen_place(usage, x, 0, grid[x]);
2916
2917     usage->spaces = snewn(cr * cr, struct gridgen_coord);
2918     usage->nspaces = 0;
2919
2920     usage->rs = rs;
2921
2922     /*
2923      * Initialise the list of grid spaces, taking care to leave
2924      * out the row I've already filled in above.
2925      */
2926     for (y = 1; y < cr; y++) {
2927         for (x = 0; x < cr; x++) {
2928             usage->spaces[usage->nspaces].x = x;
2929             usage->spaces[usage->nspaces].y = y;
2930             usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2931             usage->nspaces++;
2932         }
2933     }
2934
2935     /*
2936      * Run the real generator function.
2937      */
2938     ret = gridgen_real(usage, grid, &maxsteps);
2939
2940     /*
2941      * Clean up the usage structure now we have our answer.
2942      */
2943     sfree(usage->spaces);
2944     sfree(usage->cge);
2945     sfree(usage->blk);
2946     sfree(usage->col);
2947     sfree(usage->row);
2948     sfree(usage);
2949
2950     return ret;
2951 }
2952
2953 /* ----------------------------------------------------------------------
2954  * End of grid generator code.
2955  */
2956
2957 static int check_killer_cage_sum(struct block_structure *kblocks,
2958                                  digit *kgrid, digit *grid, int blk)
2959 {
2960     /*
2961      * Returns: -1 if the cage has any empty square; 0 if all squares
2962      * are full but the sum is wrong; +1 if all squares are full and
2963      * they have the right sum.
2964      *
2965      * Does not check uniqueness of numbers within the cage; that's
2966      * done elsewhere (because in error highlighting it needs to be
2967      * detected separately so as to flag the error in a visually
2968      * different way).
2969      */
2970     int n_squares = kblocks->nr_squares[blk];
2971     int sum = 0, clue = 0;
2972     int i;
2973
2974     for (i = 0; i < n_squares; i++) {
2975         int xy = kblocks->blocks[blk][i];
2976
2977         if (grid[xy] == 0)
2978             return -1;
2979         sum += grid[xy];
2980
2981         if (kgrid[xy]) {
2982             assert(clue == 0);
2983             clue = kgrid[xy];
2984         }
2985     }
2986
2987     assert(clue != 0);
2988     return sum == clue;
2989 }
2990
2991 /*
2992  * Check whether a grid contains a valid complete puzzle.
2993  */
2994 static int check_valid(int cr, struct block_structure *blocks,
2995                        struct block_structure *kblocks,
2996                        digit *kgrid, int xtype, digit *grid)
2997 {
2998     unsigned char *used;
2999     int x, y, i, j, n;
3000
3001     used = snewn(cr, unsigned char);
3002
3003     /*
3004      * Check that each row contains precisely one of everything.
3005      */
3006     for (y = 0; y < cr; y++) {
3007         memset(used, FALSE, cr);
3008         for (x = 0; x < cr; x++)
3009             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
3010                 used[grid[y*cr+x]-1] = TRUE;
3011         for (n = 0; n < cr; n++)
3012             if (!used[n]) {
3013                 sfree(used);
3014                 return FALSE;
3015             }
3016     }
3017
3018     /*
3019      * Check that each column contains precisely one of everything.
3020      */
3021     for (x = 0; x < cr; x++) {
3022         memset(used, FALSE, cr);
3023         for (y = 0; y < cr; y++)
3024             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
3025                 used[grid[y*cr+x]-1] = TRUE;
3026         for (n = 0; n < cr; n++)
3027             if (!used[n]) {
3028                 sfree(used);
3029                 return FALSE;
3030             }
3031     }
3032
3033     /*
3034      * Check that each block contains precisely one of everything.
3035      */
3036     for (i = 0; i < cr; i++) {
3037         memset(used, FALSE, cr);
3038         for (j = 0; j < cr; j++)
3039             if (grid[blocks->blocks[i][j]] > 0 &&
3040                 grid[blocks->blocks[i][j]] <= cr)
3041                 used[grid[blocks->blocks[i][j]]-1] = TRUE;
3042         for (n = 0; n < cr; n++)
3043             if (!used[n]) {
3044                 sfree(used);
3045                 return FALSE;
3046             }
3047     }
3048
3049     /*
3050      * Check that each Killer cage, if any, contains at most one of
3051      * everything. If we also know the clues for those cages (which we
3052      * might not, when this function is called early in puzzle
3053      * generation), we also check that they all have the right sum.
3054      */
3055     if (kblocks) {
3056         for (i = 0; i < kblocks->nr_blocks; i++) {
3057             memset(used, FALSE, cr);
3058             for (j = 0; j < kblocks->nr_squares[i]; j++)
3059                 if (grid[kblocks->blocks[i][j]] > 0 &&
3060                     grid[kblocks->blocks[i][j]] <= cr) {
3061                     if (used[grid[kblocks->blocks[i][j]]-1]) {
3062                         sfree(used);
3063                         return FALSE;
3064                     }
3065                     used[grid[kblocks->blocks[i][j]]-1] = TRUE;
3066                 }
3067
3068             if (kgrid && check_killer_cage_sum(kblocks, kgrid, grid, i) != 1) {
3069                 sfree(used);
3070                 return FALSE;
3071             }
3072         }
3073     }
3074
3075     /*
3076      * Check that each diagonal contains precisely one of everything.
3077      */
3078     if (xtype) {
3079         memset(used, FALSE, cr);
3080         for (i = 0; i < cr; i++)
3081             if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
3082                 used[grid[diag0(i)]-1] = TRUE;
3083         for (n = 0; n < cr; n++)
3084             if (!used[n]) {
3085                 sfree(used);
3086                 return FALSE;
3087             }
3088         for (i = 0; i < cr; i++)
3089             if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
3090                 used[grid[diag1(i)]-1] = TRUE;
3091         for (n = 0; n < cr; n++)
3092             if (!used[n]) {
3093                 sfree(used);
3094                 return FALSE;
3095             }
3096     }
3097
3098     sfree(used);
3099     return TRUE;
3100 }
3101
3102 static int symmetries(const game_params *params, int x, int y,
3103                       int *output, int s)
3104 {
3105     int c = params->c, r = params->r, cr = c*r;
3106     int i = 0;
3107
3108 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
3109
3110     ADD(x, y);
3111
3112     switch (s) {
3113       case SYMM_NONE:
3114         break;                         /* just x,y is all we need */
3115       case SYMM_ROT2:
3116         ADD(cr - 1 - x, cr - 1 - y);
3117         break;
3118       case SYMM_ROT4:
3119         ADD(cr - 1 - y, x);
3120         ADD(y, cr - 1 - x);
3121         ADD(cr - 1 - x, cr - 1 - y);
3122         break;
3123       case SYMM_REF2:
3124         ADD(cr - 1 - x, y);
3125         break;
3126       case SYMM_REF2D:
3127         ADD(y, x);
3128         break;
3129       case SYMM_REF4:
3130         ADD(cr - 1 - x, y);
3131         ADD(x, cr - 1 - y);
3132         ADD(cr - 1 - x, cr - 1 - y);
3133         break;
3134       case SYMM_REF4D:
3135         ADD(y, x);
3136         ADD(cr - 1 - x, cr - 1 - y);
3137         ADD(cr - 1 - y, cr - 1 - x);
3138         break;
3139       case SYMM_REF8:
3140         ADD(cr - 1 - x, y);
3141         ADD(x, cr - 1 - y);
3142         ADD(cr - 1 - x, cr - 1 - y);
3143         ADD(y, x);
3144         ADD(y, cr - 1 - x);
3145         ADD(cr - 1 - y, x);
3146         ADD(cr - 1 - y, cr - 1 - x);
3147         break;
3148     }
3149
3150 #undef ADD
3151
3152     return i;
3153 }
3154
3155 static char *encode_solve_move(int cr, digit *grid)
3156 {
3157     int i, len;
3158     char *ret, *p;
3159     const char *sep;
3160
3161     /*
3162      * It's surprisingly easy to work out _exactly_ how long this
3163      * string needs to be. To decimal-encode all the numbers from 1
3164      * to n:
3165      * 
3166      *  - every number has a units digit; total is n.
3167      *  - all numbers above 9 have a tens digit; total is max(n-9,0).
3168      *  - all numbers above 99 have a hundreds digit; total is max(n-99,0).
3169      *  - and so on.
3170      */
3171     len = 0;
3172     for (i = 1; i <= cr; i *= 10)
3173         len += max(cr - i + 1, 0);
3174     len += cr;                 /* don't forget the commas */
3175     len *= cr;                 /* there are cr rows of these */
3176
3177     /*
3178      * Now len is one bigger than the total size of the
3179      * comma-separated numbers (because we counted an
3180      * additional leading comma). We need to have a leading S
3181      * and a trailing NUL, so we're off by one in total.
3182      */
3183     len++;
3184
3185     ret = snewn(len, char);
3186     p = ret;
3187     *p++ = 'S';
3188     sep = "";
3189     for (i = 0; i < cr*cr; i++) {
3190         p += sprintf(p, "%s%d", sep, grid[i]);
3191         sep = ",";
3192     }
3193     *p++ = '\0';
3194     assert(p - ret == len);
3195
3196     return ret;
3197 }
3198
3199 static void dsf_to_blocks(int *dsf, struct block_structure *blocks,
3200                           int min_expected, int max_expected)
3201 {
3202     int cr = blocks->c * blocks->r, area = cr * cr;
3203     int i, nb = 0;
3204
3205     for (i = 0; i < area; i++)
3206         blocks->whichblock[i] = -1;
3207     for (i = 0; i < area; i++) {
3208         int j = dsf_canonify(dsf, i);
3209         if (blocks->whichblock[j] < 0)
3210             blocks->whichblock[j] = nb++;
3211         blocks->whichblock[i] = blocks->whichblock[j];
3212     }
3213     assert(nb >= min_expected && nb <= max_expected);
3214     blocks->nr_blocks = nb;
3215 }
3216
3217 static void make_blocks_from_whichblock(struct block_structure *blocks)
3218 {
3219     int i;
3220
3221     for (i = 0; i < blocks->nr_blocks; i++) {
3222         blocks->blocks[i][blocks->max_nr_squares-1] = 0;
3223         blocks->nr_squares[i] = 0;
3224     }
3225     for (i = 0; i < blocks->area; i++) {
3226         int b = blocks->whichblock[i];
3227         int j = blocks->blocks[b][blocks->max_nr_squares-1]++;
3228         assert(j < blocks->max_nr_squares);
3229         blocks->blocks[b][j] = i;
3230         blocks->nr_squares[b]++;
3231     }
3232 }
3233
3234 static char *encode_block_structure_desc(char *p, struct block_structure *blocks)
3235 {
3236     int i, currrun = 0;
3237     int c = blocks->c, r = blocks->r, cr = c * r;
3238
3239     /*
3240      * Encode the block structure. We do this by encoding
3241      * the pattern of dividing lines: first we iterate
3242      * over the cr*(cr-1) internal vertical grid lines in
3243      * ordinary reading order, then over the cr*(cr-1)
3244      * internal horizontal ones in transposed reading
3245      * order.
3246      * 
3247      * We encode the number of non-lines between the
3248      * lines; _ means zero (two adjacent divisions), a
3249      * means 1, ..., y means 25, and z means 25 non-lines
3250      * _and no following line_ (so that za means 26, zb 27
3251      * etc).
3252      */
3253     for (i = 0; i <= 2*cr*(cr-1); i++) {
3254         int x, y, p0, p1, edge;
3255
3256         if (i == 2*cr*(cr-1)) {
3257             edge = TRUE;       /* terminating virtual edge */
3258         } else {
3259             if (i < cr*(cr-1)) {
3260                 y = i/(cr-1);
3261                 x = i%(cr-1);
3262                 p0 = y*cr+x;
3263                 p1 = y*cr+x+1;
3264             } else {
3265                 x = i/(cr-1) - cr;
3266                 y = i%(cr-1);
3267                 p0 = y*cr+x;
3268                 p1 = (y+1)*cr+x;
3269             }
3270             edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
3271         }
3272
3273         if (edge) {
3274             while (currrun > 25)
3275                 *p++ = 'z', currrun -= 25;
3276             if (currrun)
3277                 *p++ = 'a'-1 + currrun;
3278             else
3279                 *p++ = '_';
3280             currrun = 0;
3281         } else
3282             currrun++;
3283     }
3284     return p;
3285 }
3286
3287 static char *encode_grid(char *desc, digit *grid, int area)
3288 {
3289     int run, i;
3290     char *p = desc;
3291
3292     run = 0;
3293     for (i = 0; i <= area; i++) {
3294         int n = (i < area ? grid[i] : -1);
3295
3296         if (!n)
3297             run++;
3298         else {
3299             if (run) {
3300                 while (run > 0) {
3301                     int c = 'a' - 1 + run;
3302                     if (run > 26)
3303                         c = 'z';
3304                     *p++ = c;
3305                     run -= c - ('a' - 1);
3306                 }
3307             } else {
3308                 /*
3309                  * If there's a number in the very top left or
3310                  * bottom right, there's no point putting an
3311                  * unnecessary _ before or after it.
3312                  */
3313                 if (p > desc && n > 0)
3314                     *p++ = '_';
3315             }
3316             if (n > 0)
3317                 p += sprintf(p, "%d", n);
3318             run = 0;
3319         }
3320     }
3321     return p;
3322 }
3323
3324 /*
3325  * Conservatively stimate the number of characters required for
3326  * encoding a grid of a certain area.
3327  */
3328 static int grid_encode_space (int area)
3329 {
3330     int t, count;
3331     for (count = 1, t = area; t > 26; t -= 26)
3332         count++;
3333     return count * area;
3334 }
3335
3336 /*
3337  * Conservatively stimate the number of characters required for
3338  * encoding a given blocks structure.
3339  */
3340 static int blocks_encode_space(struct block_structure *blocks)
3341 {
3342     int cr = blocks->c * blocks->r, area = cr * cr;
3343     return grid_encode_space(area);
3344 }
3345
3346 static char *encode_puzzle_desc(const game_params *params, digit *grid,
3347                                 struct block_structure *blocks,
3348                                 digit *kgrid,
3349                                 struct block_structure *kblocks)
3350 {
3351     int c = params->c, r = params->r, cr = c*r;
3352     int area = cr*cr;
3353     char *p, *desc;
3354     int space;
3355
3356     space = grid_encode_space(area) + 1;
3357     if (r == 1)
3358         space += blocks_encode_space(blocks) + 1;
3359     if (params->killer) {
3360         space += blocks_encode_space(kblocks) + 1;
3361         space += grid_encode_space(area) + 1;
3362     }
3363     desc = snewn(space, char);
3364     p = encode_grid(desc, grid, area);
3365
3366     if (r == 1) {
3367         *p++ = ',';
3368         p = encode_block_structure_desc(p, blocks);
3369     }
3370     if (params->killer) {
3371         *p++ = ',';
3372         p = encode_block_structure_desc(p, kblocks);
3373         *p++ = ',';
3374         p = encode_grid(p, kgrid, area);
3375     }
3376     assert(p - desc < space);
3377     *p++ = '\0';
3378     desc = sresize(desc, p - desc, char);
3379
3380     return desc;
3381 }
3382
3383 static void merge_blocks(struct block_structure *b, int n1, int n2)
3384 {
3385     int i;
3386     /* Move data towards the lower block number.  */
3387     if (n2 < n1) {
3388         int t = n2;
3389         n2 = n1;
3390         n1 = t;
3391     }
3392
3393     /* Merge n2 into n1, and move the last block into n2's position.  */
3394     for (i = 0; i < b->nr_squares[n2]; i++)
3395         b->whichblock[b->blocks[n2][i]] = n1;
3396     memcpy(b->blocks[n1] + b->nr_squares[n1], b->blocks[n2],
3397            b->nr_squares[n2] * sizeof **b->blocks);
3398     b->nr_squares[n1] += b->nr_squares[n2];
3399
3400     n1 = b->nr_blocks - 1;
3401     if (n2 != n1) {
3402         memcpy(b->blocks[n2], b->blocks[n1],
3403                b->nr_squares[n1] * sizeof **b->blocks);
3404         for (i = 0; i < b->nr_squares[n1]; i++)
3405             b->whichblock[b->blocks[n1][i]] = n2;
3406         b->nr_squares[n2] = b->nr_squares[n1];
3407     }
3408     b->nr_blocks = n1;
3409 }
3410
3411 static int merge_some_cages(struct block_structure *b, int cr, int area,
3412                              digit *grid, random_state *rs)
3413 {
3414     /*
3415      * Make a list of all the pairs of adjacent blocks.
3416      */
3417     int i, j, k;
3418     struct pair {
3419         int b1, b2;
3420     } *pairs;
3421     int npairs;
3422
3423     pairs = snewn(b->nr_blocks * b->nr_blocks, struct pair);
3424     npairs = 0;
3425
3426     for (i = 0; i < b->nr_blocks; i++) {
3427         for (j = i+1; j < b->nr_blocks; j++) {
3428
3429             /*
3430              * Rule the merger out of consideration if it's
3431              * obviously not viable.
3432              */
3433             if (b->nr_squares[i] + b->nr_squares[j] > b->max_nr_squares)
3434                 continue;              /* we couldn't merge these anyway */
3435
3436             /*
3437              * See if these two blocks have a pair of squares
3438              * adjacent to each other.
3439              */
3440             for (k = 0; k < b->nr_squares[i]; k++) {
3441                 int xy = b->blocks[i][k];
3442                 int y = xy / cr, x = xy % cr;
3443                 if ((y   > 0  && b->whichblock[xy - cr] == j) ||
3444                     (y+1 < cr && b->whichblock[xy + cr] == j) ||
3445                     (x   > 0  && b->whichblock[xy -  1] == j) ||
3446                     (x+1 < cr && b->whichblock[xy +  1] == j)) {
3447                     /*
3448                      * Yes! Add this pair to our list.
3449                      */
3450                     pairs[npairs].b1 = i;
3451                     pairs[npairs].b2 = j;
3452                     break;
3453                 }
3454             }
3455         }
3456     }
3457
3458     /*
3459      * Now go through that list in random order until we find a pair
3460      * of blocks we can merge.
3461      */
3462     while (npairs > 0) {
3463         int n1, n2;
3464         unsigned int digits_found;
3465
3466         /*
3467          * Pick a random pair, and remove it from the list.
3468          */
3469         i = random_upto(rs, npairs);
3470         n1 = pairs[i].b1;
3471         n2 = pairs[i].b2;
3472         if (i != npairs-1)
3473             pairs[i] = pairs[npairs-1];
3474         npairs--;
3475
3476         /* Guarantee that the merged cage would still be a region.  */
3477         digits_found = 0;
3478         for (i = 0; i < b->nr_squares[n1]; i++)
3479             digits_found |= 1 << grid[b->blocks[n1][i]];
3480         for (i = 0; i < b->nr_squares[n2]; i++)
3481             if (digits_found & (1 << grid[b->blocks[n2][i]]))
3482                 break;
3483         if (i != b->nr_squares[n2])
3484             continue;
3485
3486         /*
3487          * Got one! Do the merge.
3488          */
3489         merge_blocks(b, n1, n2);
3490         sfree(pairs);
3491         return TRUE;
3492     }
3493
3494     sfree(pairs);
3495     return FALSE;
3496 }
3497
3498 static void compute_kclues(struct block_structure *cages, digit *kclues,
3499                            digit *grid, int area)
3500 {
3501     int i;
3502     memset(kclues, 0, area * sizeof *kclues);
3503     for (i = 0; i < cages->nr_blocks; i++) {
3504         int j, sum = 0;
3505         for (j = 0; j < area; j++)
3506             if (cages->whichblock[j] == i)
3507                 sum += grid[j];
3508         for (j = 0; j < area; j++)
3509             if (cages->whichblock[j] == i)
3510                 break;
3511         assert (j != area);
3512         kclues[j] = sum;
3513     }
3514 }
3515
3516 static struct block_structure *gen_killer_cages(int cr, random_state *rs,
3517                                                 int remove_singletons)
3518 {
3519     int nr;
3520     int x, y, area = cr * cr;
3521     int n_singletons = 0;
3522     struct block_structure *b = alloc_block_structure (1, cr, area, cr, area);
3523
3524     for (x = 0; x < area; x++)
3525         b->whichblock[x] = -1;
3526     nr = 0;
3527     for (y = 0; y < cr; y++)
3528         for (x = 0; x < cr; x++) {
3529             int rnd;
3530             int xy = y*cr+x;
3531             if (b->whichblock[xy] != -1)
3532                 continue;
3533             b->whichblock[xy] = nr;
3534
3535             rnd = random_bits(rs, 4);
3536             if (xy + 1 < area && (rnd >= 4 || (!remove_singletons && rnd >= 1))) {
3537                 int xy2 = xy + 1;
3538                 if (x + 1 == cr || b->whichblock[xy2] != -1 ||
3539                     (xy + cr < area && random_bits(rs, 1) == 0))
3540                     xy2 = xy + cr;
3541                 if (xy2 >= area)
3542                     n_singletons++;
3543                 else
3544                     b->whichblock[xy2] = nr;
3545             } else
3546                 n_singletons++;
3547             nr++;
3548         }
3549
3550     b->nr_blocks = nr;
3551     make_blocks_from_whichblock(b);
3552
3553     for (x = y = 0; x < b->nr_blocks; x++)
3554         if (b->nr_squares[x] == 1)
3555             y++;
3556     assert(y == n_singletons);
3557
3558     if (n_singletons > 0 && remove_singletons) {
3559         int n;
3560         for (n = 0; n < b->nr_blocks;) {
3561             int xy, x, y, xy2, other;
3562             if (b->nr_squares[n] > 1) {
3563                 n++;
3564                 continue;
3565             }
3566             xy = b->blocks[n][0];
3567             x = xy % cr;
3568             y = xy / cr;
3569             if (xy + 1 == area)
3570                 xy2 = xy - 1;
3571             else if (x + 1 < cr && (y + 1 == cr || random_bits(rs, 1) == 0))
3572                 xy2 = xy + 1;
3573             else
3574                 xy2 = xy + cr;
3575             other = b->whichblock[xy2];
3576
3577             if (b->nr_squares[other] == 1)
3578                 n_singletons--;
3579             n_singletons--;
3580             merge_blocks(b, n, other);
3581             if (n < other)
3582                 n++;
3583         }
3584         assert(n_singletons == 0);
3585     }
3586     return b;
3587 }
3588
3589 static char *new_game_desc(const game_params *params, random_state *rs,
3590                            char **aux, int interactive)
3591 {
3592     int c = params->c, r = params->r, cr = c*r;
3593     int area = cr*cr;
3594     struct block_structure *blocks, *kblocks;
3595     digit *grid, *grid2, *kgrid;
3596     struct xy { int x, y; } *locs;
3597     int nlocs;
3598     char *desc;
3599     int coords[16], ncoords;
3600     int x, y, i, j;
3601     struct difficulty dlev;
3602
3603     precompute_sum_bits();
3604
3605     /*
3606      * Adjust the maximum difficulty level to be consistent with
3607      * the puzzle size: all 2x2 puzzles appear to be Trivial
3608      * (DIFF_BLOCK) so we cannot hold out for even a Basic
3609      * (DIFF_SIMPLE) one.
3610      */
3611     dlev.maxdiff = params->diff;
3612     dlev.maxkdiff = params->kdiff;
3613     if (c == 2 && r == 2)
3614         dlev.maxdiff = DIFF_BLOCK;
3615
3616     grid = snewn(area, digit);
3617     locs = snewn(area, struct xy);
3618     grid2 = snewn(area, digit);
3619
3620     blocks = alloc_block_structure (c, r, area, cr, cr);
3621
3622     kblocks = NULL;
3623     kgrid = (params->killer) ? snewn(area, digit) : NULL;
3624
3625 #ifdef STANDALONE_SOLVER
3626     assert(!"This should never happen, so we don't need to create blocknames");
3627 #endif
3628
3629     /*
3630      * Loop until we get a grid of the required difficulty. This is
3631      * nasty, but it seems to be unpleasantly hard to generate
3632      * difficult grids otherwise.
3633      */
3634     while (1) {
3635         /*
3636          * Generate a random solved state, starting by
3637          * constructing the block structure.
3638          */
3639         if (r == 1) {                  /* jigsaw mode */
3640             int *dsf = divvy_rectangle(cr, cr, cr, rs);
3641
3642             dsf_to_blocks (dsf, blocks, cr, cr);
3643
3644             sfree(dsf);
3645         } else {                       /* basic Sudoku mode */
3646             for (y = 0; y < cr; y++)
3647                 for (x = 0; x < cr; x++)
3648                     blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
3649         }
3650         make_blocks_from_whichblock(blocks);
3651
3652         if (params->killer) {
3653             if (kblocks) free_block_structure(kblocks);
3654             kblocks = gen_killer_cages(cr, rs, params->kdiff > DIFF_KSINGLE);
3655         }
3656
3657         if (!gridgen(cr, blocks, kblocks, params->xtype, grid, rs, area*area))
3658             continue;
3659         assert(check_valid(cr, blocks, kblocks, NULL, params->xtype, grid));
3660
3661         /*
3662          * Save the solved grid in aux.
3663          */
3664         {
3665             /*
3666              * We might already have written *aux the last time we
3667              * went round this loop, in which case we should free
3668              * the old aux before overwriting it with the new one.
3669              */
3670             if (*aux) {
3671                 sfree(*aux);
3672             }
3673
3674             *aux = encode_solve_move(cr, grid);
3675         }
3676
3677         /*
3678          * Now we have a solved grid. For normal puzzles, we start removing
3679          * things from it while preserving solubility.  Killer puzzles are
3680          * different: we just pass the empty grid to the solver, and use
3681          * the puzzle if it comes back solved.
3682          */
3683
3684         if (params->killer) {
3685             struct block_structure *good_cages = NULL;
3686             struct block_structure *last_cages = NULL;
3687             int ntries = 0;
3688
3689             memcpy(grid2, grid, area);
3690
3691             for (;;) {
3692                 compute_kclues(kblocks, kgrid, grid2, area);
3693
3694                 memset(grid, 0, area * sizeof *grid);
3695                 solver(cr, blocks, kblocks, params->xtype, grid, kgrid, &dlev);
3696                 if (dlev.diff == dlev.maxdiff && dlev.kdiff == dlev.maxkdiff) {
3697                     /*
3698                      * We have one that matches our difficulty.  Store it for
3699                      * later, but keep going.
3700                      */
3701                     if (good_cages)
3702                         free_block_structure(good_cages);
3703                     ntries = 0;
3704                     good_cages = dup_block_structure(kblocks);
3705                     if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3706                         break;
3707                 } else if (dlev.diff > dlev.maxdiff || dlev.kdiff > dlev.maxkdiff) {
3708                     /*
3709                      * Give up after too many tries and either use the good one we
3710                      * found, or generate a new grid.
3711                      */
3712                     if (++ntries > 50)
3713                         break;
3714                     /*
3715                      * The difficulty level got too high.  If we have a good
3716                      * one, use it, otherwise go back to the last one that
3717                      * was at a lower difficulty and restart the process from
3718                      * there.
3719                      */
3720                     if (good_cages != NULL) {
3721                         free_block_structure(kblocks);
3722                         kblocks = dup_block_structure(good_cages);
3723                         if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3724                             break;
3725                     } else {
3726                         if (last_cages == NULL)
3727                             break;
3728                         free_block_structure(kblocks);
3729                         kblocks = last_cages;
3730                         last_cages = NULL;
3731                     }
3732                 } else {
3733                     if (last_cages)
3734                         free_block_structure(last_cages);
3735                     last_cages = dup_block_structure(kblocks);
3736                     if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3737                         break;
3738                 }
3739             }
3740             if (last_cages)
3741                 free_block_structure(last_cages);
3742             if (good_cages != NULL) {
3743                 free_block_structure(kblocks);
3744                 kblocks = good_cages;
3745                 compute_kclues(kblocks, kgrid, grid2, area);
3746                 memset(grid, 0, area * sizeof *grid);
3747                 break;
3748             }
3749             continue;
3750         }
3751
3752         /*
3753          * Find the set of equivalence classes of squares permitted
3754          * by the selected symmetry. We do this by enumerating all
3755          * the grid squares which have no symmetric companion
3756          * sorting lower than themselves.
3757          */
3758         nlocs = 0;
3759         for (y = 0; y < cr; y++)
3760             for (x = 0; x < cr; x++) {
3761                 int i = y*cr+x;
3762                 int j;
3763
3764                 ncoords = symmetries(params, x, y, coords, params->symm);
3765                 for (j = 0; j < ncoords; j++)
3766                     if (coords[2*j+1]*cr+coords[2*j] < i)
3767                         break;
3768                 if (j == ncoords) {
3769                     locs[nlocs].x = x;
3770                     locs[nlocs].y = y;
3771                     nlocs++;
3772                 }
3773             }
3774
3775         /*
3776          * Now shuffle that list.
3777          */
3778         shuffle(locs, nlocs, sizeof(*locs), rs);
3779
3780         /*
3781          * Now loop over the shuffled list and, for each element,
3782          * see whether removing that element (and its reflections)
3783          * from the grid will still leave the grid soluble.
3784          */
3785         for (i = 0; i < nlocs; i++) {
3786             x = locs[i].x;
3787             y = locs[i].y;
3788
3789             memcpy(grid2, grid, area);
3790             ncoords = symmetries(params, x, y, coords, params->symm);
3791             for (j = 0; j < ncoords; j++)
3792                 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
3793
3794             solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3795             if (dlev.diff <= dlev.maxdiff &&
3796                 (!params->killer || dlev.kdiff <= dlev.maxkdiff)) {
3797                 for (j = 0; j < ncoords; j++)
3798                     grid[coords[2*j+1]*cr+coords[2*j]] = 0;
3799             }
3800         }
3801
3802         memcpy(grid2, grid, area);
3803
3804         solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3805         if (dlev.diff == dlev.maxdiff &&
3806             (!params->killer || dlev.kdiff == dlev.maxkdiff))
3807             break;                     /* found one! */
3808     }
3809
3810     sfree(grid2);
3811     sfree(locs);
3812
3813     /*
3814      * Now we have the grid as it will be presented to the user.
3815      * Encode it in a game desc.
3816      */
3817     desc = encode_puzzle_desc(params, grid, blocks, kgrid, kblocks);
3818
3819     sfree(grid);
3820     free_block_structure(blocks);
3821     if (params->killer) {
3822         free_block_structure(kblocks);
3823         sfree(kgrid);
3824     }
3825
3826     return desc;
3827 }
3828
3829 static const char *spec_to_grid(const char *desc, digit *grid, int area)
3830 {
3831     int i = 0;
3832     while (*desc && *desc != ',') {
3833         int n = *desc++;
3834         if (n >= 'a' && n <= 'z') {
3835             int run = n - 'a' + 1;
3836             assert(i + run <= area);
3837             while (run-- > 0)
3838                 grid[i++] = 0;
3839         } else if (n == '_') {
3840             /* do nothing */;
3841         } else if (n > '0' && n <= '9') {
3842             assert(i < area);
3843             grid[i++] = atoi(desc-1);
3844             while (*desc >= '0' && *desc <= '9')
3845                 desc++;
3846         } else {
3847             assert(!"We can't get here");
3848         }
3849     }
3850     assert(i == area);
3851     return desc;
3852 }
3853
3854 /*
3855  * Create a DSF from a spec found in *pdesc. Update this to point past the
3856  * end of the block spec, and return an error string or NULL if everything
3857  * is OK. The DSF is stored in *PDSF.
3858  */
3859 static const char *spec_to_dsf(const char **pdesc, int **pdsf,
3860                                int cr, int area)
3861 {
3862     const char *desc = *pdesc;
3863     int pos = 0;
3864     int *dsf;
3865
3866     *pdsf = dsf = snew_dsf(area);
3867
3868     while (*desc && *desc != ',') {
3869         int c, adv;
3870
3871         if (*desc == '_')
3872             c = 0;
3873         else if (*desc >= 'a' && *desc <= 'z')
3874             c = *desc - 'a' + 1;
3875         else {
3876             sfree(dsf);
3877             return "Invalid character in game description";
3878         }
3879         desc++;
3880
3881         adv = (c != 26);               /* 'z' is a special case */
3882
3883         while (c-- > 0) {
3884             int p0, p1;
3885
3886             /*
3887              * Non-edge; merge the two dsf classes on either
3888              * side of it.
3889              */
3890             if (pos >= 2*cr*(cr-1)) {
3891                 sfree(dsf);
3892                 return "Too much data in block structure specification";
3893             }
3894
3895             if (pos < cr*(cr-1)) {
3896                 int y = pos/(cr-1);
3897                 int x = pos%(cr-1);
3898                 p0 = y*cr+x;
3899                 p1 = y*cr+x+1;
3900             } else {
3901                 int x = pos/(cr-1) - cr;
3902                 int y = pos%(cr-1);
3903                 p0 = y*cr+x;
3904                 p1 = (y+1)*cr+x;
3905             }
3906             dsf_merge(dsf, p0, p1);
3907
3908             pos++;
3909         }
3910         if (adv)
3911             pos++;
3912     }
3913     *pdesc = desc;
3914
3915     /*
3916      * When desc is exhausted, we expect to have gone exactly
3917      * one space _past_ the end of the grid, due to the dummy
3918      * edge at the end.
3919      */
3920     if (pos != 2*cr*(cr-1)+1) {
3921         sfree(dsf);
3922         return "Not enough data in block structure specification";
3923     }
3924
3925     return NULL;
3926 }
3927
3928 static const char *validate_grid_desc(const char **pdesc, int range, int area)
3929 {
3930     const char *desc = *pdesc;
3931     int squares = 0;
3932     while (*desc && *desc != ',') {
3933         int n = *desc++;
3934         if (n >= 'a' && n <= 'z') {
3935             squares += n - 'a' + 1;
3936         } else if (n == '_') {
3937             /* do nothing */;
3938         } else if (n > '0' && n <= '9') {
3939             int val = atoi(desc-1);
3940             if (val < 1 || val > range)
3941                 return "Out-of-range number in game description";
3942             squares++;
3943             while (*desc >= '0' && *desc <= '9')
3944                 desc++;
3945         } else
3946             return "Invalid character in game description";
3947     }
3948
3949     if (squares < area)
3950         return "Not enough data to fill grid";
3951
3952     if (squares > area)
3953         return "Too much data to fit in grid";
3954     *pdesc = desc;
3955     return NULL;
3956 }
3957
3958 static const char *validate_block_desc(const char **pdesc, int cr, int area,
3959                                        int min_nr_blocks, int max_nr_blocks,
3960                                        int min_nr_squares, int max_nr_squares)
3961 {
3962     const char *err;
3963     int *dsf;
3964
3965     err = spec_to_dsf(pdesc, &dsf, cr, area);
3966     if (err) {
3967         return err;
3968     }
3969
3970     if (min_nr_squares == max_nr_squares) {
3971         assert(min_nr_blocks == max_nr_blocks);
3972         assert(min_nr_blocks * min_nr_squares == area);
3973     }
3974     /*
3975      * Now we've got our dsf. Verify that it matches
3976      * expectations.
3977      */
3978     {
3979         int *canons, *counts;
3980         int i, j, c, ncanons = 0;
3981
3982         canons = snewn(max_nr_blocks, int);
3983         counts = snewn(max_nr_blocks, int);
3984
3985         for (i = 0; i < area; i++) {
3986             j = dsf_canonify(dsf, i);
3987
3988             for (c = 0; c < ncanons; c++)
3989                 if (canons[c] == j) {
3990                     counts[c]++;
3991                     if (counts[c] > max_nr_squares) {
3992                         sfree(dsf);
3993                         sfree(canons);
3994                         sfree(counts);
3995                         return "A jigsaw block is too big";
3996                     }
3997                     break;
3998                 }
3999
4000             if (c == ncanons) {
4001                 if (ncanons >= max_nr_blocks) {
4002                     sfree(dsf);
4003                     sfree(canons);
4004                     sfree(counts);
4005                     return "Too many distinct jigsaw blocks";
4006                 }
4007                 canons[ncanons] = j;
4008                 counts[ncanons] = 1;
4009                 ncanons++;
4010             }
4011         }
4012
4013         if (ncanons < min_nr_blocks) {
4014             sfree(dsf);
4015             sfree(canons);
4016             sfree(counts);
4017             return "Not enough distinct jigsaw blocks";
4018         }
4019         for (c = 0; c < ncanons; c++) {
4020             if (counts[c] < min_nr_squares) {
4021                 sfree(dsf);
4022                 sfree(canons);
4023                 sfree(counts);
4024                 return "A jigsaw block is too small";
4025             }
4026         }
4027         sfree(canons);
4028         sfree(counts);
4029     }
4030
4031     sfree(dsf);
4032     return NULL;
4033 }
4034
4035 static const char *validate_desc(const game_params *params, const char *desc)
4036 {
4037     int cr = params->c * params->r, area = cr*cr;
4038     const char *err;
4039
4040     err = validate_grid_desc(&desc, cr, area);
4041     if (err)
4042         return err;
4043
4044     if (params->r == 1) {
4045         /*
4046          * Now we expect a suffix giving the jigsaw block
4047          * structure. Parse it and validate that it divides the
4048          * grid into the right number of regions which are the
4049          * right size.
4050          */
4051         if (*desc != ',')
4052             return "Expected jigsaw block structure in game description";
4053         desc++;
4054         err = validate_block_desc(&desc, cr, area, cr, cr, cr, cr);
4055         if (err)
4056             return err;
4057
4058     }
4059     if (params->killer) {
4060         if (*desc != ',')
4061             return "Expected killer block structure in game description";
4062         desc++;
4063         err = validate_block_desc(&desc, cr, area, cr, area, 2, cr);
4064         if (err)
4065             return err;
4066         if (*desc != ',')
4067             return "Expected killer clue grid in game description";
4068         desc++;
4069         err = validate_grid_desc(&desc, cr * area, area);
4070         if (err)
4071             return err;
4072     }
4073     if (*desc)
4074         return "Unexpected data at end of game description";
4075
4076     return NULL;
4077 }
4078
4079 static game_state *new_game(midend *me, const game_params *params,
4080                             const char *desc)
4081 {
4082     game_state *state = snew(game_state);
4083     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
4084     int i;
4085
4086     precompute_sum_bits();
4087
4088     state->cr = cr;
4089     state->xtype = params->xtype;
4090     state->killer = params->killer;
4091
4092     state->grid = snewn(area, digit);
4093     state->pencil = snewn(area * cr, unsigned char);
4094     memset(state->pencil, 0, area * cr);
4095     state->immutable = snewn(area, unsigned char);
4096     memset(state->immutable, FALSE, area);
4097
4098     state->blocks = alloc_block_structure (c, r, area, cr, cr);
4099
4100     if (params->killer) {
4101         state->kblocks = alloc_block_structure (c, r, area, cr, area);
4102         state->kgrid = snewn(area, digit);
4103     } else {
4104         state->kblocks = NULL;
4105         state->kgrid = NULL;
4106     }
4107     state->completed = state->cheated = FALSE;
4108
4109     desc = spec_to_grid(desc, state->grid, area);
4110     for (i = 0; i < area; i++)
4111         if (state->grid[i] != 0)
4112             state->immutable[i] = TRUE;
4113
4114     if (r == 1) {
4115         const char *err;
4116         int *dsf;
4117         assert(*desc == ',');
4118         desc++;
4119         err = spec_to_dsf(&desc, &dsf, cr, area);
4120         assert(err == NULL);
4121         dsf_to_blocks(dsf, state->blocks, cr, cr);
4122         sfree(dsf);
4123     } else {
4124         int x, y;
4125
4126         for (y = 0; y < cr; y++)
4127             for (x = 0; x < cr; x++)
4128                 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
4129     }
4130     make_blocks_from_whichblock(state->blocks);
4131
4132     if (params->killer) {
4133         const char *err;
4134         int *dsf;
4135         assert(*desc == ',');
4136         desc++;
4137         err = spec_to_dsf(&desc, &dsf, cr, area);
4138         assert(err == NULL);
4139         dsf_to_blocks(dsf, state->kblocks, cr, area);
4140         sfree(dsf);
4141         make_blocks_from_whichblock(state->kblocks);
4142
4143         assert(*desc == ',');
4144         desc++;
4145         desc = spec_to_grid(desc, state->kgrid, area);
4146     }
4147     assert(!*desc);
4148
4149 #ifdef STANDALONE_SOLVER
4150     /*
4151      * Set up the block names for solver diagnostic output.
4152      */
4153     {
4154         char *p = (char *)(state->blocks->blocknames + cr);
4155
4156         if (r == 1) {
4157             for (i = 0; i < area; i++) {
4158                 int j = state->blocks->whichblock[i];
4159                 if (!state->blocks->blocknames[j]) {
4160                     state->blocks->blocknames[j] = p;
4161                     p += 1 + sprintf(p, "starting at (%d,%d)",
4162                                      1 + i%cr, 1 + i/cr);
4163                 }
4164             }
4165         } else {
4166             int bx, by;
4167             for (by = 0; by < r; by++)
4168                 for (bx = 0; bx < c; bx++) {
4169                     state->blocks->blocknames[by*c+bx] = p;
4170                     p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
4171                 }
4172         }
4173         assert(p - (char *)state->blocks->blocknames < (int)(cr*(sizeof(char *)+80)));
4174         for (i = 0; i < cr; i++)
4175             assert(state->blocks->blocknames[i]);
4176     }
4177 #endif
4178
4179     return state;
4180 }
4181
4182 static game_state *dup_game(const game_state *state)
4183 {
4184     game_state *ret = snew(game_state);
4185     int cr = state->cr, area = cr * cr;
4186
4187     ret->cr = state->cr;
4188     ret->xtype = state->xtype;
4189     ret->killer = state->killer;
4190
4191     ret->blocks = state->blocks;
4192     ret->blocks->refcount++;
4193
4194     ret->kblocks = state->kblocks;
4195     if (ret->kblocks)
4196         ret->kblocks->refcount++;
4197
4198     ret->grid = snewn(area, digit);
4199     memcpy(ret->grid, state->grid, area);
4200
4201     if (state->killer) {
4202         ret->kgrid = snewn(area, digit);
4203         memcpy(ret->kgrid, state->kgrid, area);
4204     } else
4205         ret->kgrid = NULL;
4206
4207     ret->pencil = snewn(area * cr, unsigned char);
4208     memcpy(ret->pencil, state->pencil, area * cr);
4209
4210     ret->immutable = snewn(area, unsigned char);
4211     memcpy(ret->immutable, state->immutable, area);
4212
4213     ret->completed = state->completed;
4214     ret->cheated = state->cheated;
4215
4216     return ret;
4217 }
4218
4219 static void free_game(game_state *state)
4220 {
4221     free_block_structure(state->blocks);
4222     if (state->kblocks)
4223         free_block_structure(state->kblocks);
4224
4225     sfree(state->immutable);
4226     sfree(state->pencil);
4227     sfree(state->grid);
4228     if (state->kgrid) sfree(state->kgrid);
4229     sfree(state);
4230 }
4231
4232 static char *solve_game(const game_state *state, const game_state *currstate,
4233                         const char *ai, const char **error)
4234 {
4235     int cr = state->cr;
4236     char *ret;
4237     digit *grid;
4238     struct difficulty dlev;
4239
4240     /*
4241      * If we already have the solution in ai, save ourselves some
4242      * time.
4243      */
4244     if (ai)
4245         return dupstr(ai);
4246
4247     grid = snewn(cr*cr, digit);
4248     memcpy(grid, state->grid, cr*cr);
4249     dlev.maxdiff = DIFF_RECURSIVE;
4250     dlev.maxkdiff = DIFF_KINTERSECT;
4251     solver(cr, state->blocks, state->kblocks, state->xtype, grid,
4252            state->kgrid, &dlev);
4253
4254     *error = NULL;
4255
4256     if (dlev.diff == DIFF_IMPOSSIBLE)
4257         *error = "No solution exists for this puzzle";
4258     else if (dlev.diff == DIFF_AMBIGUOUS)
4259         *error = "Multiple solutions exist for this puzzle";
4260
4261     if (*error) {
4262         sfree(grid);
4263         return NULL;
4264     }
4265
4266     ret = encode_solve_move(cr, grid);
4267
4268     sfree(grid);
4269
4270     return ret;
4271 }
4272
4273 static char *grid_text_format(int cr, struct block_structure *blocks,
4274                               int xtype, digit *grid)
4275 {
4276     int vmod, hmod;
4277     int x, y;
4278     int totallen, linelen, nlines;
4279     char *ret, *p, ch;
4280
4281     /*
4282      * For non-jigsaw Sudoku, we format in the way we always have,
4283      * by having the digits unevenly spaced so that the dividing
4284      * lines can fit in:
4285      *
4286      * . . | . .
4287      * . . | . .
4288      * ----+----
4289      * . . | . .
4290      * . . | . .
4291      *
4292      * For jigsaw puzzles, however, we must leave space between
4293      * _all_ pairs of digits for an optional dividing line, so we
4294      * have to move to the rather ugly
4295      * 
4296      * .   .   .   .
4297      * ------+------
4298      * .   . | .   .
4299      *       +---+  
4300      * .   . | . | .
4301      * ------+   |  
4302      * .   .   . | .
4303      * 
4304      * We deal with both cases using the same formatting code; we
4305      * simply invent a vmod value such that there's a vertical
4306      * dividing line before column i iff i is divisible by vmod
4307      * (so it's r in the first case and 1 in the second), and hmod
4308      * likewise for horizontal dividing lines.
4309      */
4310
4311     if (blocks->r != 1) {
4312         vmod = blocks->r;
4313         hmod = blocks->c;
4314     } else {
4315         vmod = hmod = 1;
4316     }
4317
4318     /*
4319      * Line length: we have cr digits, each with a space after it,
4320      * and (cr-1)/vmod dividing lines, each with a space after it.
4321      * The final space is replaced by a newline, but that doesn't
4322      * affect the length.
4323      */
4324     linelen = 2*(cr + (cr-1)/vmod);
4325
4326     /*
4327      * Number of lines: we have cr rows of digits, and (cr-1)/hmod
4328      * dividing rows.
4329      */
4330     nlines = cr + (cr-1)/hmod;
4331
4332     /*
4333      * Allocate the space.
4334      */
4335     totallen = linelen * nlines;
4336     ret = snewn(totallen+1, char);     /* leave room for terminating NUL */
4337
4338     /*
4339      * Write the text.
4340      */
4341     p = ret;
4342     for (y = 0; y < cr; y++) {
4343         /*
4344          * Row of digits.
4345          */
4346         for (x = 0; x < cr; x++) {
4347             /*
4348              * Digit.
4349              */
4350             digit d = grid[y*cr+x];
4351
4352             if (d == 0) {
4353                 /*
4354                  * Empty space: we usually write a dot, but we'll
4355                  * highlight spaces on the X-diagonals (in X mode)
4356                  * by using underscores instead.
4357                  */
4358                 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
4359                     ch = '_';
4360                 else
4361                     ch = '.';
4362             } else if (d <= 9) {
4363                 ch = '0' + d;
4364             } else {
4365                 ch = 'a' + d-10;
4366             }
4367
4368             *p++ = ch;
4369             if (x == cr-1) {
4370                 *p++ = '\n';
4371                 continue;
4372             }
4373             *p++ = ' ';
4374
4375             if ((x+1) % vmod)
4376                 continue;
4377
4378             /*
4379              * Optional dividing line.
4380              */
4381             if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
4382                 ch = '|';
4383             else
4384                 ch = ' ';
4385             *p++ = ch;
4386             *p++ = ' ';
4387         }
4388         if (y == cr-1 || (y+1) % hmod)
4389             continue;
4390
4391         /*
4392          * Dividing row.
4393          */
4394         for (x = 0; x < cr; x++) {
4395             int dwid;
4396             int tl, tr, bl, br;
4397
4398             /*
4399              * Division between two squares. This varies
4400              * complicatedly in length.
4401              */
4402             dwid = 2;                  /* digit and its following space */
4403             if (x == cr-1)
4404                 dwid--;                /* no following space at end of line */
4405             if (x > 0 && x % vmod == 0)
4406                 dwid++;                /* preceding space after a divider */
4407
4408             if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
4409                 ch = '-';
4410             else
4411                 ch = ' ';
4412
4413             while (dwid-- > 0)
4414                 *p++ = ch;
4415
4416             if (x == cr-1) {
4417                 *p++ = '\n';
4418                 break;
4419             }
4420
4421             if ((x+1) % vmod)
4422                 continue;
4423
4424             /*
4425              * Corner square. This is:
4426              *  - a space if all four surrounding squares are in
4427              *    the same block
4428              *  - a vertical line if the two left ones are in one
4429              *    block and the two right in another
4430              *  - a horizontal line if the two top ones are in one
4431              *    block and the two bottom in another
4432              *  - a plus sign in all other cases. (If we had a
4433              *    richer character set available we could break
4434              *    this case up further by doing fun things with
4435              *    line-drawing T-pieces.)
4436              */
4437             tl = blocks->whichblock[y*cr+x];
4438             tr = blocks->whichblock[y*cr+x+1];
4439             bl = blocks->whichblock[(y+1)*cr+x];
4440             br = blocks->whichblock[(y+1)*cr+x+1];
4441
4442             if (tl == tr && tr == bl && bl == br)
4443                 ch = ' ';
4444             else if (tl == bl && tr == br)
4445                 ch = '|';
4446             else if (tl == tr && bl == br)
4447                 ch = '-';
4448             else
4449                 ch = '+';
4450
4451             *p++ = ch;
4452         }
4453     }
4454
4455     assert(p - ret == totallen);
4456     *p = '\0';
4457     return ret;
4458 }
4459
4460 static int game_can_format_as_text_now(const game_params *params)
4461 {
4462     /*
4463      * Formatting Killer puzzles as text is currently unsupported. I
4464      * can't think of any sensible way of doing it which doesn't
4465      * involve expanding the puzzle to such a large scale as to make
4466      * it unusable.
4467      */
4468     if (params->killer)
4469         return FALSE;
4470     return TRUE;
4471 }
4472
4473 static char *game_text_format(const game_state *state)
4474 {
4475     assert(!state->kblocks);
4476     return grid_text_format(state->cr, state->blocks, state->xtype,
4477                             state->grid);
4478 }
4479
4480 struct game_ui {
4481     /*
4482      * These are the coordinates of the currently highlighted
4483      * square on the grid, if hshow = 1.
4484      */
4485     int hx, hy;
4486     /*
4487      * This indicates whether the current highlight is a
4488      * pencil-mark one or a real one.
4489      */
4490     int hpencil;
4491     /*
4492      * This indicates whether or not we're showing the highlight
4493      * (used to be hx = hy = -1); important so that when we're
4494      * using the cursor keys it doesn't keep coming back at a
4495      * fixed position. When hshow = 1, pressing a valid number
4496      * or letter key or Space will enter that number or letter in the grid.
4497      */
4498     int hshow;
4499     /*
4500      * This indicates whether we're using the highlight as a cursor;
4501      * it means that it doesn't vanish on a keypress, and that it is
4502      * allowed on immutable squares.
4503      */
4504     int hcursor;
4505 };
4506
4507 static game_ui *new_ui(const game_state *state)
4508 {
4509     game_ui *ui = snew(game_ui);
4510
4511     ui->hx = ui->hy = 0;
4512     ui->hpencil = ui->hshow = ui->hcursor = 0;
4513
4514     return ui;
4515 }
4516
4517 static void free_ui(game_ui *ui)
4518 {
4519     sfree(ui);
4520 }
4521
4522 static char *encode_ui(const game_ui *ui)
4523 {
4524     return NULL;
4525 }
4526
4527 static void decode_ui(game_ui *ui, const char *encoding)
4528 {
4529 }
4530
4531 static void game_changed_state(game_ui *ui, const game_state *oldstate,
4532                                const game_state *newstate)
4533 {
4534     int cr = newstate->cr;
4535     /*
4536      * We prevent pencil-mode highlighting of a filled square, unless
4537      * we're using the cursor keys. So if the user has just filled in
4538      * a square which we had a pencil-mode highlight in (by Undo, or
4539      * by Redo, or by Solve), then we cancel the highlight.
4540      */
4541     if (ui->hshow && ui->hpencil && !ui->hcursor &&
4542         newstate->grid[ui->hy * cr + ui->hx] != 0) {
4543         ui->hshow = 0;
4544     }
4545 }
4546
4547 struct game_drawstate {
4548     int started;
4549     int cr, xtype;
4550     int tilesize;
4551     digit *grid;
4552     unsigned char *pencil;
4553     unsigned char *hl;
4554     /* This is scratch space used within a single call to game_redraw. */
4555     int nregions, *entered_items;
4556 };
4557
4558 static char *interpret_move(const game_state *state, game_ui *ui,
4559                             const game_drawstate *ds,
4560                             int x, int y, int button)
4561 {
4562     int cr = state->cr;
4563     int tx, ty;
4564     char buf[80];
4565
4566     button &= ~MOD_MASK;
4567
4568     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4569     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4570
4571     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
4572         if (button == LEFT_BUTTON) {
4573             if (state->immutable[ty*cr+tx]) {
4574                 ui->hshow = 0;
4575             } else if (tx == ui->hx && ty == ui->hy &&
4576                        ui->hshow && ui->hpencil == 0) {
4577                 ui->hshow = 0;
4578             } else {
4579                 ui->hx = tx;
4580                 ui->hy = ty;
4581                 ui->hshow = 1;
4582                 ui->hpencil = 0;
4583             }
4584             ui->hcursor = 0;
4585             return UI_UPDATE;
4586         }
4587         if (button == RIGHT_BUTTON) {
4588             /*
4589              * Pencil-mode highlighting for non filled squares.
4590              */
4591             if (state->grid[ty*cr+tx] == 0) {
4592                 if (tx == ui->hx && ty == ui->hy &&
4593                     ui->hshow && ui->hpencil) {
4594                     ui->hshow = 0;
4595                 } else {
4596                     ui->hpencil = 1;
4597                     ui->hx = tx;
4598                     ui->hy = ty;
4599                     ui->hshow = 1;
4600                 }
4601             } else {
4602                 ui->hshow = 0;
4603             }
4604             ui->hcursor = 0;
4605             return UI_UPDATE;
4606         }
4607     }
4608     if (IS_CURSOR_MOVE(button)) {
4609         move_cursor(button, &ui->hx, &ui->hy, cr, cr, 0);
4610         ui->hshow = ui->hcursor = 1;
4611         return UI_UPDATE;
4612     }
4613     if (ui->hshow &&
4614         (button == CURSOR_SELECT)) {
4615         ui->hpencil = 1 - ui->hpencil;
4616         ui->hcursor = 1;
4617         return UI_UPDATE;
4618     }
4619
4620     if (ui->hshow &&
4621         ((button >= '0' && button <= '9' && button - '0' <= cr) ||
4622          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
4623          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
4624          button == CURSOR_SELECT2 || button == '\b')) {
4625         int n = button - '0';
4626         if (button >= 'A' && button <= 'Z')
4627             n = button - 'A' + 10;
4628         if (button >= 'a' && button <= 'z')
4629             n = button - 'a' + 10;
4630         if (button == CURSOR_SELECT2 || button == '\b')
4631             n = 0;
4632
4633         /*
4634          * Can't overwrite this square. This can only happen here
4635          * if we're using the cursor keys.
4636          */
4637         if (state->immutable[ui->hy*cr+ui->hx])
4638             return NULL;
4639
4640         /*
4641          * Can't make pencil marks in a filled square. Again, this
4642          * can only become highlighted if we're using cursor keys.
4643          */
4644         if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
4645             return NULL;
4646
4647         sprintf(buf, "%c%d,%d,%d",
4648                 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
4649
4650         if (!ui->hcursor) ui->hshow = 0;
4651
4652         return dupstr(buf);
4653     }
4654
4655     if (button == 'M' || button == 'm')
4656         return dupstr("M");
4657
4658     return NULL;
4659 }
4660
4661 static game_state *execute_move(const game_state *from, const char *move)
4662 {
4663     int cr = from->cr;
4664     game_state *ret;
4665     int x, y, n;
4666
4667     if (move[0] == 'S') {
4668         const char *p;
4669
4670         ret = dup_game(from);
4671         ret->completed = ret->cheated = TRUE;
4672
4673         p = move+1;
4674         for (n = 0; n < cr*cr; n++) {
4675             ret->grid[n] = atoi(p);
4676
4677             if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
4678                 free_game(ret);
4679                 return NULL;
4680             }
4681
4682             while (*p && isdigit((unsigned char)*p)) p++;
4683             if (*p == ',') p++;
4684         }
4685
4686         return ret;
4687     } else if ((move[0] == 'P' || move[0] == 'R') &&
4688         sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
4689         x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
4690
4691         ret = dup_game(from);
4692         if (move[0] == 'P' && n > 0) {
4693             int index = (y*cr+x) * cr + (n-1);
4694             ret->pencil[index] = !ret->pencil[index];
4695         } else {
4696             ret->grid[y*cr+x] = n;
4697             memset(ret->pencil + (y*cr+x)*cr, 0, cr);
4698
4699             /*
4700              * We've made a real change to the grid. Check to see
4701              * if the game has been completed.
4702              */
4703             if (!ret->completed && check_valid(
4704                     cr, ret->blocks, ret->kblocks, ret->kgrid,
4705                     ret->xtype, ret->grid)) {
4706                 ret->completed = TRUE;
4707             }
4708         }
4709         return ret;
4710     } else if (move[0] == 'M') {
4711         /*
4712          * Fill in absolutely all pencil marks in unfilled squares,
4713          * for those who like to play by the rigorous approach of
4714          * starting off in that state and eliminating things.
4715          */
4716         ret = dup_game(from);
4717         for (y = 0; y < cr; y++) {
4718             for (x = 0; x < cr; x++) {
4719                 if (!ret->grid[y*cr+x]) {
4720                     memset(ret->pencil + (y*cr+x)*cr, 1, cr);
4721                 }
4722             }
4723         }
4724         return ret;
4725     } else
4726         return NULL;                   /* couldn't parse move string */
4727 }
4728
4729 /* ----------------------------------------------------------------------
4730  * Drawing routines.
4731  */
4732
4733 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
4734 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
4735
4736 static void game_compute_size(const game_params *params, int tilesize,
4737                               int *x, int *y)
4738 {
4739     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
4740     struct { int tilesize; } ads, *ds = &ads;
4741     ads.tilesize = tilesize;
4742
4743     *x = SIZE(params->c * params->r);
4744     *y = SIZE(params->c * params->r);
4745 }
4746
4747 static void game_set_size(drawing *dr, game_drawstate *ds,
4748                           const game_params *params, int tilesize)
4749 {
4750     ds->tilesize = tilesize;
4751 }
4752
4753 static float *game_colours(frontend *fe, int *ncolours)
4754 {
4755     float *ret = snewn(3 * NCOLOURS, float);
4756
4757     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
4758
4759     ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
4760     ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
4761     ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
4762
4763     ret[COL_GRID * 3 + 0] = 0.0F;
4764     ret[COL_GRID * 3 + 1] = 0.0F;
4765     ret[COL_GRID * 3 + 2] = 0.0F;
4766
4767     ret[COL_CLUE * 3 + 0] = 0.0F;
4768     ret[COL_CLUE * 3 + 1] = 0.0F;
4769     ret[COL_CLUE * 3 + 2] = 0.0F;
4770
4771     ret[COL_USER * 3 + 0] = 0.0F;
4772     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
4773     ret[COL_USER * 3 + 2] = 0.0F;
4774
4775     ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
4776     ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
4777     ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
4778
4779     ret[COL_ERROR * 3 + 0] = 1.0F;
4780     ret[COL_ERROR * 3 + 1] = 0.0F;
4781     ret[COL_ERROR * 3 + 2] = 0.0F;
4782
4783     ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4784     ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4785     ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
4786
4787     ret[COL_KILLER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4788     ret[COL_KILLER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4789     ret[COL_KILLER * 3 + 2] = 0.1F * ret[COL_BACKGROUND * 3 + 2];
4790
4791     *ncolours = NCOLOURS;
4792     return ret;
4793 }
4794
4795 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
4796 {
4797     struct game_drawstate *ds = snew(struct game_drawstate);
4798     int cr = state->cr;
4799
4800     ds->started = FALSE;
4801     ds->cr = cr;
4802     ds->xtype = state->xtype;
4803     ds->grid = snewn(cr*cr, digit);
4804     memset(ds->grid, cr+2, cr*cr);
4805     ds->pencil = snewn(cr*cr*cr, digit);
4806     memset(ds->pencil, 0, cr*cr*cr);
4807     ds->hl = snewn(cr*cr, unsigned char);
4808     memset(ds->hl, 0, cr*cr);
4809     /*
4810      * ds->entered_items needs one row of cr entries per entity in
4811      * which digits may not be duplicated. That's one for each row,
4812      * each column, each block, each diagonal, and each Killer cage.
4813      */
4814     ds->nregions = cr*3 + 2;
4815     if (state->kblocks)
4816         ds->nregions += state->kblocks->nr_blocks;
4817     ds->entered_items = snewn(cr * ds->nregions, int);
4818     ds->tilesize = 0;                  /* not decided yet */
4819     return ds;
4820 }
4821
4822 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
4823 {
4824     sfree(ds->hl);
4825     sfree(ds->pencil);
4826     sfree(ds->grid);
4827     sfree(ds->entered_items);
4828     sfree(ds);
4829 }
4830
4831 static void draw_number(drawing *dr, game_drawstate *ds,
4832                         const game_state *state, int x, int y, int hl)
4833 {
4834     int cr = state->cr;
4835     int tx, ty, tw, th;
4836     int cx, cy, cw, ch;
4837     int col_killer = (hl & 32 ? COL_ERROR : COL_KILLER);
4838     char str[20];
4839
4840     if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
4841         ds->hl[y*cr+x] == hl &&
4842         !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
4843         return;                        /* no change required */
4844
4845     tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
4846     ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
4847
4848     cx = tx;
4849     cy = ty;
4850     cw = tw = TILE_SIZE-1-2*GRIDEXTRA;
4851     ch = th = TILE_SIZE-1-2*GRIDEXTRA;
4852
4853     if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
4854         cx -= GRIDEXTRA, cw += GRIDEXTRA;
4855     if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
4856         cw += GRIDEXTRA;
4857     if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
4858         cy -= GRIDEXTRA, ch += GRIDEXTRA;
4859     if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
4860         ch += GRIDEXTRA;
4861
4862     clip(dr, cx, cy, cw, ch);
4863
4864     /* background needs erasing */
4865     draw_rect(dr, cx, cy, cw, ch,
4866               ((hl & 15) == 1 ? COL_HIGHLIGHT :
4867                (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
4868                COL_BACKGROUND));
4869
4870     /*
4871      * Draw the corners of thick lines in corner-adjacent squares,
4872      * which jut into this square by one pixel.
4873      */
4874     if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
4875         draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4876     if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
4877         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4878     if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
4879         draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4880     if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
4881         draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4882
4883     /* pencil-mode highlight */
4884     if ((hl & 15) == 2) {
4885         int coords[6];
4886         coords[0] = cx;
4887         coords[1] = cy;
4888         coords[2] = cx+cw/2;
4889         coords[3] = cy;
4890         coords[4] = cx;
4891         coords[5] = cy+ch/2;
4892         draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
4893     }
4894
4895     if (state->kblocks) {
4896         int t = GRIDEXTRA * 3;
4897         int kcx, kcy, kcw, kch;
4898         int kl, kt, kr, kb;
4899         int has_left = 0, has_right = 0, has_top = 0, has_bottom = 0;
4900
4901         /*
4902          * In non-jigsaw mode, the Killer cages are placed at a
4903          * fixed offset from the outer edge of the cell dividing
4904          * lines, so that they look right whether those lines are
4905          * thick or thin. In jigsaw mode, however, doing this will
4906          * sometimes cause the cage outlines in adjacent squares to
4907          * fail to match up with each other, so we must offset a
4908          * fixed amount from the _centre_ of the cell dividing
4909          * lines.
4910          */
4911         if (state->blocks->r == 1) {
4912             kcx = tx;
4913             kcy = ty;
4914             kcw = tw;
4915             kch = th;
4916         } else {
4917             kcx = cx;
4918             kcy = cy;
4919             kcw = cw;
4920             kch = ch;
4921         }
4922         kl = kcx - 1;
4923         kt = kcy - 1;
4924         kr = kcx + kcw;
4925         kb = kcy + kch;
4926
4927         /*
4928          * First, draw the lines dividing this area from neighbouring
4929          * different areas.
4930          */
4931         if (x == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x-1])
4932             has_left = 1, kl += t;
4933         if (x+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x+1])
4934             has_right = 1, kr -= t;
4935         if (y == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x])
4936             has_top = 1, kt += t;
4937         if (y+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x])
4938             has_bottom = 1, kb -= t;
4939         if (has_top)
4940             draw_line(dr, kl, kt, kr, kt, col_killer);
4941         if (has_bottom)
4942             draw_line(dr, kl, kb, kr, kb, col_killer);
4943         if (has_left)
4944             draw_line(dr, kl, kt, kl, kb, col_killer);
4945         if (has_right)
4946             draw_line(dr, kr, kt, kr, kb, col_killer);
4947         /*
4948          * Now, take care of the corners (just as for the normal borders).
4949          * We only need a corner if there wasn't a full edge.
4950          */
4951         if (x > 0 && y > 0 && !has_left && !has_top
4952             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x-1])
4953         {
4954             draw_line(dr, kl, kt + t, kl + t, kt + t, col_killer);
4955             draw_line(dr, kl + t, kt, kl + t, kt + t, col_killer);
4956         }
4957         if (x+1 < cr && y > 0 && !has_right && !has_top
4958             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x+1])
4959         {
4960             draw_line(dr, kcx + kcw - t, kt + t, kcx + kcw, kt + t, col_killer);
4961             draw_line(dr, kcx + kcw - t, kt, kcx + kcw - t, kt + t, col_killer);
4962         }
4963         if (x > 0 && y+1 < cr && !has_left && !has_bottom
4964             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x-1])
4965         {
4966             draw_line(dr, kl, kcy + kch - t, kl + t, kcy + kch - t, col_killer);
4967             draw_line(dr, kl + t, kcy + kch - t, kl + t, kcy + kch, col_killer);
4968         }
4969         if (x+1 < cr && y+1 < cr && !has_right && !has_bottom
4970             && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x+1])
4971         {
4972             draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw - t, kcy + kch, col_killer);
4973             draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw, kcy + kch - t, col_killer);
4974         }
4975
4976     }
4977
4978     if (state->killer && state->kgrid[y*cr+x]) {
4979         sprintf (str, "%d", state->kgrid[y*cr+x]);
4980         draw_text(dr, tx + GRIDEXTRA * 4, ty + GRIDEXTRA * 4 + TILE_SIZE/4,
4981                   FONT_VARIABLE, TILE_SIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
4982                   col_killer, str);
4983     }
4984
4985     /* new number needs drawing? */
4986     if (state->grid[y*cr+x]) {
4987         str[1] = '\0';
4988         str[0] = state->grid[y*cr+x] + '0';
4989         if (str[0] > '9')
4990             str[0] += 'a' - ('9'+1);
4991         draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
4992                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
4993                   state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
4994     } else {
4995         int i, j, npencil;
4996         int pl, pr, pt, pb;
4997         float bestsize;
4998         int pw, ph, minph, pbest, fontsize;
4999
5000         /* Count the pencil marks required. */
5001         for (i = npencil = 0; i < cr; i++)
5002             if (state->pencil[(y*cr+x)*cr+i])
5003                 npencil++;
5004         if (npencil) {
5005
5006             minph = 2;
5007
5008             /*
5009              * Determine the bounding rectangle within which we're going
5010              * to put the pencil marks.
5011              */
5012             /* Start with the whole square */
5013             pl = tx + GRIDEXTRA;
5014             pr = pl + TILE_SIZE - GRIDEXTRA;
5015             pt = ty + GRIDEXTRA;
5016             pb = pt + TILE_SIZE - GRIDEXTRA;
5017             if (state->killer) {
5018                 /*
5019                  * Make space for the Killer cages. We do this
5020                  * unconditionally, for uniformity between squares,
5021                  * rather than making it depend on whether a Killer
5022                  * cage edge is actually present on any given side.
5023                  */
5024                 pl += GRIDEXTRA * 3;
5025                 pr -= GRIDEXTRA * 3;
5026                 pt += GRIDEXTRA * 3;
5027                 pb -= GRIDEXTRA * 3;
5028                 if (state->kgrid[y*cr+x] != 0) {
5029                     /* Make further space for the Killer number. */
5030                     pt += TILE_SIZE/4;
5031                     /* minph--; */
5032                 }
5033             }
5034
5035             /*
5036              * We arrange our pencil marks in a grid layout, with
5037              * the number of rows and columns adjusted to allow the
5038              * maximum font size.
5039              *
5040              * So now we work out what the grid size ought to be.
5041              */
5042             bestsize = 0.0;
5043             pbest = 0;
5044             /* Minimum */
5045             for (pw = 3; pw < max(npencil,4); pw++) {
5046                 float fw, fh, fs;
5047
5048                 ph = (npencil + pw - 1) / pw;
5049                 ph = max(ph, minph);
5050                 fw = (pr - pl) / (float)pw;
5051                 fh = (pb - pt) / (float)ph;
5052                 fs = min(fw, fh);
5053                 if (fs > bestsize) {
5054                     bestsize = fs;
5055                     pbest = pw;
5056                 }
5057             }
5058             assert(pbest > 0);
5059             pw = pbest;
5060             ph = (npencil + pw - 1) / pw;
5061             ph = max(ph, minph);
5062
5063             /*
5064              * Now we've got our grid dimensions, work out the pixel
5065              * size of a grid element, and round it to the nearest
5066              * pixel. (We don't want rounding errors to make the
5067              * grid look uneven at low pixel sizes.)
5068              */
5069             fontsize = min((pr - pl) / pw, (pb - pt) / ph);
5070
5071             /*
5072              * Centre the resulting figure in the square.
5073              */
5074             pl = tx + (TILE_SIZE - fontsize * pw) / 2;
5075             pt = ty + (TILE_SIZE - fontsize * ph) / 2;
5076
5077             /*
5078              * And move it down a bit if it's collided with the
5079              * Killer cage number.
5080              */
5081             if (state->killer && state->kgrid[y*cr+x] != 0) {
5082                 pt = max(pt, ty + GRIDEXTRA * 3 + TILE_SIZE/4);
5083             }
5084
5085             /*
5086              * Now actually draw the pencil marks.
5087              */
5088             for (i = j = 0; i < cr; i++)
5089                 if (state->pencil[(y*cr+x)*cr+i]) {
5090                     int dx = j % pw, dy = j / pw;
5091
5092                     str[1] = '\0';
5093                     str[0] = i + '1';
5094                     if (str[0] > '9')
5095                         str[0] += 'a' - ('9'+1);
5096                     draw_text(dr, pl + fontsize * (2*dx+1) / 2,
5097                               pt + fontsize * (2*dy+1) / 2,
5098                               FONT_VARIABLE, fontsize,
5099                               ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
5100                     j++;
5101                 }
5102         }
5103     }
5104
5105     unclip(dr);
5106
5107     draw_update(dr, cx, cy, cw, ch);
5108
5109     ds->grid[y*cr+x] = state->grid[y*cr+x];
5110     memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
5111     ds->hl[y*cr+x] = hl;
5112 }
5113
5114 static void game_redraw(drawing *dr, game_drawstate *ds,
5115                         const game_state *oldstate, const game_state *state,
5116                         int dir, const game_ui *ui,
5117                         float animtime, float flashtime)
5118 {
5119     int cr = state->cr;
5120     int x, y;
5121
5122     if (!ds->started) {
5123         /*
5124          * The initial contents of the window are not guaranteed
5125          * and can vary with front ends. To be on the safe side,
5126          * all games should start by drawing a big
5127          * background-colour rectangle covering the whole window.
5128          */
5129         draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
5130
5131         /*
5132          * Draw the grid. We draw it as a big thick rectangle of
5133          * COL_GRID initially; individual calls to draw_number()
5134          * will poke the right-shaped holes in it.
5135          */
5136         draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
5137                   cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
5138                   COL_GRID);
5139     }
5140
5141     /*
5142      * This array is used to keep track of rows, columns and boxes
5143      * which contain a number more than once.
5144      */
5145     for (x = 0; x < cr * ds->nregions; x++)
5146         ds->entered_items[x] = 0;
5147     for (x = 0; x < cr; x++)
5148         for (y = 0; y < cr; y++) {
5149             digit d = state->grid[y*cr+x];
5150             if (d) {
5151                 int box, kbox;
5152
5153                 /* Rows */
5154                 ds->entered_items[x*cr+d-1]++;
5155
5156                 /* Columns */
5157                 ds->entered_items[(y+cr)*cr+d-1]++;
5158
5159                 /* Blocks */
5160                 box = state->blocks->whichblock[y*cr+x];
5161                 ds->entered_items[(box+2*cr)*cr+d-1]++;
5162
5163                 /* Diagonals */
5164                 if (ds->xtype) {
5165                     if (ondiag0(y*cr+x))
5166                         ds->entered_items[(3*cr)*cr+d-1]++;
5167                     if (ondiag1(y*cr+x))
5168                         ds->entered_items[(3*cr+1)*cr+d-1]++;
5169                 }
5170
5171                 /* Killer cages */
5172                 if (state->kblocks) {
5173                     kbox = state->kblocks->whichblock[y*cr+x];
5174                     ds->entered_items[(kbox+3*cr+2)*cr+d-1]++;
5175                 }
5176             }
5177         }
5178
5179     /*
5180      * Draw any numbers which need redrawing.
5181      */
5182     for (x = 0; x < cr; x++) {
5183         for (y = 0; y < cr; y++) {
5184             int highlight = 0;
5185             digit d = state->grid[y*cr+x];
5186
5187             if (flashtime > 0 &&
5188                 (flashtime <= FLASH_TIME/3 ||
5189                  flashtime >= FLASH_TIME*2/3))
5190                 highlight = 1;
5191
5192             /* Highlight active input areas. */
5193             if (x == ui->hx && y == ui->hy && ui->hshow)
5194                 highlight = ui->hpencil ? 2 : 1;
5195
5196             /* Mark obvious errors (ie, numbers which occur more than once
5197              * in a single row, column, or box). */
5198             if (d && (ds->entered_items[x*cr+d-1] > 1 ||
5199                       ds->entered_items[(y+cr)*cr+d-1] > 1 ||
5200                       ds->entered_items[(state->blocks->whichblock[y*cr+x]
5201                                          +2*cr)*cr+d-1] > 1 ||
5202                       (ds->xtype && ((ondiag0(y*cr+x) &&
5203                                       ds->entered_items[(3*cr)*cr+d-1] > 1) ||
5204                                      (ondiag1(y*cr+x) &&
5205                                       ds->entered_items[(3*cr+1)*cr+d-1]>1)))||
5206                       (state->kblocks &&
5207                        ds->entered_items[(state->kblocks->whichblock[y*cr+x]
5208                                           +3*cr+2)*cr+d-1] > 1)))
5209                 highlight |= 16;
5210
5211             if (d && state->kblocks) {
5212                 if (check_killer_cage_sum(
5213                         state->kblocks, state->kgrid, state->grid,
5214                         state->kblocks->whichblock[y*cr+x]) == 0)
5215                     highlight |= 32;
5216             }
5217
5218             draw_number(dr, ds, state, x, y, highlight);
5219         }
5220     }
5221
5222     /*
5223      * Update the _entire_ grid if necessary.
5224      */
5225     if (!ds->started) {
5226         draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
5227         ds->started = TRUE;
5228     }
5229 }
5230
5231 static float game_anim_length(const game_state *oldstate,
5232                               const game_state *newstate, int dir, game_ui *ui)
5233 {
5234     return 0.0F;
5235 }
5236
5237 static float game_flash_length(const game_state *oldstate,
5238                                const game_state *newstate, int dir, game_ui *ui)
5239 {
5240     if (!oldstate->completed && newstate->completed &&
5241         !oldstate->cheated && !newstate->cheated)
5242         return FLASH_TIME;
5243     return 0.0F;
5244 }
5245
5246 static int game_status(const game_state *state)
5247 {
5248     return state->completed ? +1 : 0;
5249 }
5250
5251 static int game_timing_state(const game_state *state, game_ui *ui)
5252 {
5253     if (state->completed)
5254         return FALSE;
5255     return TRUE;
5256 }
5257
5258 static void game_print_size(const game_params *params, float *x, float *y)
5259 {
5260     int pw, ph;
5261
5262     /*
5263      * I'll use 9mm squares by default. They should be quite big
5264      * for this game, because players will want to jot down no end
5265      * of pencil marks in the squares.
5266      */
5267     game_compute_size(params, 900, &pw, &ph);
5268     *x = pw / 100.0F;
5269     *y = ph / 100.0F;
5270 }
5271
5272 /*
5273  * Subfunction to draw the thick lines between cells. In order to do
5274  * this using the line-drawing rather than rectangle-drawing API (so
5275  * as to get line thicknesses to scale correctly) and yet have
5276  * correctly mitred joins between lines, we must do this by tracing
5277  * the boundary of each sub-block and drawing it in one go as a
5278  * single polygon.
5279  *
5280  * This subfunction is also reused with thinner dotted lines to
5281  * outline the Killer cages, this time offsetting the outline toward
5282  * the interior of the affected squares.
5283  */
5284 static void outline_block_structure(drawing *dr, game_drawstate *ds,
5285                                     const game_state *state,
5286                                     struct block_structure *blocks,
5287                                     int ink, int inset)
5288 {
5289     int cr = state->cr;
5290     int *coords;
5291     int bi, i, n;
5292     int x, y, dx, dy, sx, sy, sdx, sdy;
5293
5294     /*
5295      * Maximum perimeter of a k-omino is 2k+2. (Proof: start
5296      * with k unconnected squares, with total perimeter 4k.
5297      * Now repeatedly join two disconnected components
5298      * together into a larger one; every time you do so you
5299      * remove at least two unit edges, and you require k-1 of
5300      * these operations to create a single connected piece, so
5301      * you must have at most 4k-2(k-1) = 2k+2 unit edges left
5302      * afterwards.)
5303      */
5304     coords = snewn(4*cr+4, int);   /* 2k+2 points, 2 coords per point */
5305
5306     /*
5307      * Iterate over all the blocks.
5308      */
5309     for (bi = 0; bi < blocks->nr_blocks; bi++) {
5310         if (blocks->nr_squares[bi] == 0)
5311             continue;
5312
5313         /*
5314          * For each block, find a starting square within it
5315          * which has a boundary at the left.
5316          */
5317         for (i = 0; i < cr; i++) {
5318             int j = blocks->blocks[bi][i];
5319             if (j % cr == 0 || blocks->whichblock[j-1] != bi)
5320                 break;
5321         }
5322         assert(i < cr); /* every block must have _some_ leftmost square */
5323         x = blocks->blocks[bi][i] % cr;
5324         y = blocks->blocks[bi][i] / cr;
5325         dx = -1;
5326         dy = 0;
5327
5328         /*
5329          * Now begin tracing round the perimeter. At all
5330          * times, (x,y) describes some square within the
5331          * block, and (x+dx,y+dy) is some adjacent square
5332          * outside it; so the edge between those two squares
5333          * is always an edge of the block.
5334          */
5335         sx = x, sy = y, sdx = dx, sdy = dy;   /* save starting position */
5336         n = 0;
5337         do {
5338             int cx, cy, tx, ty, nin;
5339
5340             /*
5341              * Advance to the next edge, by looking at the two
5342              * squares beyond it. If they're both outside the block,
5343              * we turn right (by leaving x,y the same and rotating
5344              * dx,dy clockwise); if they're both inside, we turn
5345              * left (by rotating dx,dy anticlockwise and contriving
5346              * to leave x+dx,y+dy unchanged); if one of each, we go
5347              * straight on (and may enforce by assertion that
5348              * they're one of each the _right_ way round).
5349              */
5350             nin = 0;
5351             tx = x - dy + dx;
5352             ty = y + dx + dy;
5353             nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5354                     blocks->whichblock[ty*cr+tx] == bi);
5355             tx = x - dy;
5356             ty = y + dx;
5357             nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5358                     blocks->whichblock[ty*cr+tx] == bi);
5359             if (nin == 0) {
5360                 /*
5361                  * Turn right.
5362                  */
5363                 int tmp;
5364                 tmp = dx;
5365                 dx = -dy;
5366                 dy = tmp;
5367             } else if (nin == 2) {
5368                 /*
5369                  * Turn left.
5370                  */
5371                 int tmp;
5372
5373                 x += dx;
5374                 y += dy;
5375
5376                 tmp = dx;
5377                 dx = dy;
5378                 dy = -tmp;
5379
5380                 x -= dx;
5381                 y -= dy;
5382             } else {
5383                 /*
5384                  * Go straight on.
5385                  */
5386                 x -= dy;
5387                 y += dx;
5388             }
5389
5390             /*
5391              * Now enforce by assertion that we ended up
5392              * somewhere sensible.
5393              */
5394             assert(x >= 0 && x < cr && y >= 0 && y < cr &&
5395                    blocks->whichblock[y*cr+x] == bi);
5396             assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
5397                    blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
5398
5399             /*
5400              * Record the point we just went past at one end of the
5401              * edge. To do this, we translate (x,y) down and right
5402              * by half a unit (so they're describing a point in the
5403              * _centre_ of the square) and then translate back again
5404              * in a manner rotated by dy and dx.
5405              */
5406             assert(n < 2*cr+2);
5407             cx = ((2*x+1) + dy + dx) / 2;
5408             cy = ((2*y+1) - dx + dy) / 2;
5409             coords[2*n+0] = BORDER + cx * TILE_SIZE;
5410             coords[2*n+1] = BORDER + cy * TILE_SIZE;
5411             coords[2*n+0] -= dx * inset;
5412             coords[2*n+1] -= dy * inset;
5413             if (nin == 0) {
5414                 /*
5415                  * We turned right, so inset this corner back along
5416                  * the edge towards the centre of the square.
5417                  */
5418                 coords[2*n+0] -= dy * inset;
5419                 coords[2*n+1] += dx * inset;
5420             } else if (nin == 2) {
5421                 /*
5422                  * We turned left, so inset this corner further
5423                  * _out_ along the edge into the next square.
5424                  */
5425                 coords[2*n+0] += dy * inset;
5426                 coords[2*n+1] -= dx * inset;
5427             }
5428             n++;
5429
5430         } while (x != sx || y != sy || dx != sdx || dy != sdy);
5431
5432         /*
5433          * That's our polygon; now draw it.
5434          */
5435         draw_polygon(dr, coords, n, -1, ink);
5436     }
5437
5438     sfree(coords);
5439 }
5440
5441 static void game_print(drawing *dr, const game_state *state, int tilesize)
5442 {
5443     int cr = state->cr;
5444     int ink = print_mono_colour(dr, 0);
5445     int x, y;
5446
5447     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
5448     game_drawstate ads, *ds = &ads;
5449     game_set_size(dr, ds, NULL, tilesize);
5450
5451     /*
5452      * Border.
5453      */
5454     print_line_width(dr, 3 * TILE_SIZE / 40);
5455     draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
5456
5457     /*
5458      * Highlight X-diagonal squares.
5459      */
5460     if (state->xtype) {
5461         int i;
5462         int xhighlight = print_grey_colour(dr, 0.90F);
5463
5464         for (i = 0; i < cr; i++)
5465             draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
5466                       TILE_SIZE, TILE_SIZE, xhighlight);
5467         for (i = 0; i < cr; i++)
5468             if (i*2 != cr-1)  /* avoid redoing centre square, just for fun */
5469                 draw_rect(dr, BORDER + i*TILE_SIZE,
5470                           BORDER + (cr-1-i)*TILE_SIZE,
5471                           TILE_SIZE, TILE_SIZE, xhighlight);
5472     }
5473
5474     /*
5475      * Main grid.
5476      */
5477     for (x = 1; x < cr; x++) {
5478         print_line_width(dr, TILE_SIZE / 40);
5479         draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
5480                   BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
5481     }
5482     for (y = 1; y < cr; y++) {
5483         print_line_width(dr, TILE_SIZE / 40);
5484         draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
5485                   BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
5486     }
5487
5488     /*
5489      * Thick lines between cells.
5490      */
5491     print_line_width(dr, 3 * TILE_SIZE / 40);
5492     outline_block_structure(dr, ds, state, state->blocks, ink, 0);
5493
5494     /*
5495      * Killer cages and their totals.
5496      */
5497     if (state->kblocks) {
5498         print_line_width(dr, TILE_SIZE / 40);
5499         print_line_dotted(dr, TRUE);
5500         outline_block_structure(dr, ds, state, state->kblocks, ink,
5501                                 5 * TILE_SIZE / 40);
5502         print_line_dotted(dr, FALSE);
5503         for (y = 0; y < cr; y++)
5504             for (x = 0; x < cr; x++)
5505                 if (state->kgrid[y*cr+x]) {
5506                     char str[20];
5507                     sprintf(str, "%d", state->kgrid[y*cr+x]);
5508                     draw_text(dr,
5509                               BORDER+x*TILE_SIZE + 7*TILE_SIZE/40,
5510                               BORDER+y*TILE_SIZE + 16*TILE_SIZE/40,
5511                               FONT_VARIABLE, TILE_SIZE/4,
5512                               ALIGN_VNORMAL | ALIGN_HLEFT,
5513                               ink, str);
5514                 }
5515     }
5516
5517     /*
5518      * Standard (non-Killer) clue numbers.
5519      */
5520     for (y = 0; y < cr; y++)
5521         for (x = 0; x < cr; x++)
5522             if (state->grid[y*cr+x]) {
5523                 char str[2];
5524                 str[1] = '\0';
5525                 str[0] = state->grid[y*cr+x] + '0';
5526                 if (str[0] > '9')
5527                     str[0] += 'a' - ('9'+1);
5528                 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
5529                           BORDER + y*TILE_SIZE + TILE_SIZE/2,
5530                           FONT_VARIABLE, TILE_SIZE/2,
5531                           ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
5532             }
5533 }
5534
5535 #ifdef COMBINED
5536 #define thegame solo
5537 #endif
5538
5539 const struct game thegame = {
5540     "Solo", "games.solo", "solo",
5541     default_params,
5542     game_fetch_preset, NULL,
5543     decode_params,
5544     encode_params,
5545     free_params,
5546     dup_params,
5547     TRUE, game_configure, custom_params,
5548     validate_params,
5549     new_game_desc,
5550     validate_desc,
5551     new_game,
5552     dup_game,
5553     free_game,
5554     TRUE, solve_game,
5555     TRUE, game_can_format_as_text_now, game_text_format,
5556     new_ui,
5557     free_ui,
5558     encode_ui,
5559     decode_ui,
5560     game_changed_state,
5561     interpret_move,
5562     execute_move,
5563     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
5564     game_colours,
5565     game_new_drawstate,
5566     game_free_drawstate,
5567     game_redraw,
5568     game_anim_length,
5569     game_flash_length,
5570     game_status,
5571     TRUE, FALSE, game_print_size, game_print,
5572     FALSE,                             /* wants_statusbar */
5573     FALSE, game_timing_state,
5574     REQUIRE_RBUTTON | REQUIRE_NUMPAD,  /* flags */
5575 };
5576
5577 #ifdef STANDALONE_SOLVER
5578
5579 int main(int argc, char **argv)
5580 {
5581     game_params *p;
5582     game_state *s;
5583     char *id = NULL, *desc;
5584     const char *err;
5585     int grade = FALSE;
5586     struct difficulty dlev;
5587
5588     while (--argc > 0) {
5589         char *p = *++argv;
5590         if (!strcmp(p, "-v")) {
5591             solver_show_working = TRUE;
5592         } else if (!strcmp(p, "-g")) {
5593             grade = TRUE;
5594         } else if (*p == '-') {
5595             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
5596             return 1;
5597         } else {
5598             id = p;
5599         }
5600     }
5601
5602     if (!id) {
5603         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
5604         return 1;
5605     }
5606
5607     desc = strchr(id, ':');
5608     if (!desc) {
5609         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
5610         return 1;
5611     }
5612     *desc++ = '\0';
5613
5614     p = default_params();
5615     decode_params(p, id);
5616     err = validate_desc(p, desc);
5617     if (err) {
5618         fprintf(stderr, "%s: %s\n", argv[0], err);
5619         return 1;
5620     }
5621     s = new_game(NULL, p, desc);
5622
5623     dlev.maxdiff = DIFF_RECURSIVE;
5624     dlev.maxkdiff = DIFF_KINTERSECT;
5625     solver(s->cr, s->blocks, s->kblocks, s->xtype, s->grid, s->kgrid, &dlev);
5626     if (grade) {
5627         printf("Difficulty rating: %s\n",
5628                dlev.diff==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
5629                dlev.diff==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
5630                dlev.diff==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
5631                dlev.diff==DIFF_SET ? "Advanced (set elimination required)":
5632                dlev.diff==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
5633                dlev.diff==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
5634                dlev.diff==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
5635                dlev.diff==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
5636                "INTERNAL ERROR: unrecognised difficulty code");
5637         if (p->killer)
5638             printf("Killer difficulty: %s\n",
5639                    dlev.kdiff==DIFF_KSINGLE ? "Trivial (single square cages only)":
5640                    dlev.kdiff==DIFF_KMINMAX ? "Simple (maximum sum analysis required)":
5641                    dlev.kdiff==DIFF_KSUMS ? "Intermediate (sum possibilities)":
5642                    dlev.kdiff==DIFF_KINTERSECT ? "Advanced (sum region intersections)":
5643                    "INTERNAL ERROR: unrecognised difficulty code");
5644     } else {
5645         printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
5646     }
5647
5648     return 0;
5649 }
5650
5651 #endif
5652
5653 /* vim: set shiftwidth=4 tabstop=8: */