chiark / gitweb /
Pattern: missing special case in the solver.
[sgt-puzzles.git] / pattern.c
1 /*
2  * pattern.c: the pattern-reconstruction game known as `nonograms'.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <ctype.h>
10 #include <math.h>
11
12 #include "puzzles.h"
13
14 enum {
15     COL_BACKGROUND,
16     COL_EMPTY,
17     COL_FULL,
18     COL_TEXT,
19     COL_UNKNOWN,
20     COL_GRID,
21     COL_CURSOR,
22     COL_ERROR,
23     NCOLOURS
24 };
25
26 #define PREFERRED_TILE_SIZE 24
27 #define TILE_SIZE (ds->tilesize)
28 #define BORDER (3 * TILE_SIZE / 4)
29 #define TLBORDER(d) ( (d) / 5 + 2 )
30 #define GUTTER (TILE_SIZE / 2)
31
32 #define FROMCOORD(d, x) \
33         ( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
34
35 #define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
36 #define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
37
38 #define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
39
40 struct game_params {
41     int w, h;
42 };
43
44 #define GRID_UNKNOWN 2
45 #define GRID_FULL 1
46 #define GRID_EMPTY 0
47
48 typedef struct game_state_common {
49     /* Parts of the game state that don't change during play. */
50     int w, h;
51     int rowsize;
52     int *rowdata, *rowlen;
53     unsigned char *immutable;
54     int refcount;
55 } game_state_common;
56
57 struct game_state {
58     game_state_common *common;
59     unsigned char *grid;
60     int completed, cheated;
61 };
62
63 #define FLASH_TIME 0.13F
64
65 static game_params *default_params(void)
66 {
67     game_params *ret = snew(game_params);
68
69     ret->w = ret->h = 15;
70
71     return ret;
72 }
73
74 static const struct game_params pattern_presets[] = {
75     {10, 10},
76     {15, 15},
77     {20, 20},
78 #ifndef SLOW_SYSTEM
79     {25, 25},
80     {30, 30},
81 #endif
82 };
83
84 static int game_fetch_preset(int i, char **name, game_params **params)
85 {
86     game_params *ret;
87     char str[80];
88
89     if (i < 0 || i >= lenof(pattern_presets))
90         return FALSE;
91
92     ret = snew(game_params);
93     *ret = pattern_presets[i];
94
95     sprintf(str, "%dx%d", ret->w, ret->h);
96
97     *name = dupstr(str);
98     *params = ret;
99     return TRUE;
100 }
101
102 static void free_params(game_params *params)
103 {
104     sfree(params);
105 }
106
107 static game_params *dup_params(const game_params *params)
108 {
109     game_params *ret = snew(game_params);
110     *ret = *params;                    /* structure copy */
111     return ret;
112 }
113
114 static void decode_params(game_params *ret, char const *string)
115 {
116     char const *p = string;
117
118     ret->w = atoi(p);
119     while (*p && isdigit((unsigned char)*p)) p++;
120     if (*p == 'x') {
121         p++;
122         ret->h = atoi(p);
123         while (*p && isdigit((unsigned char)*p)) p++;
124     } else {
125         ret->h = ret->w;
126     }
127 }
128
129 static char *encode_params(const game_params *params, int full)
130 {
131     char ret[400];
132     int len;
133
134     len = sprintf(ret, "%dx%d", params->w, params->h);
135     assert(len < lenof(ret));
136     ret[len] = '\0';
137
138     return dupstr(ret);
139 }
140
141 static config_item *game_configure(const game_params *params)
142 {
143     config_item *ret;
144     char buf[80];
145
146     ret = snewn(3, config_item);
147
148     ret[0].name = "Width";
149     ret[0].type = C_STRING;
150     sprintf(buf, "%d", params->w);
151     ret[0].sval = dupstr(buf);
152     ret[0].ival = 0;
153
154     ret[1].name = "Height";
155     ret[1].type = C_STRING;
156     sprintf(buf, "%d", params->h);
157     ret[1].sval = dupstr(buf);
158     ret[1].ival = 0;
159
160     ret[2].name = NULL;
161     ret[2].type = C_END;
162     ret[2].sval = NULL;
163     ret[2].ival = 0;
164
165     return ret;
166 }
167
168 static game_params *custom_params(const config_item *cfg)
169 {
170     game_params *ret = snew(game_params);
171
172     ret->w = atoi(cfg[0].sval);
173     ret->h = atoi(cfg[1].sval);
174
175     return ret;
176 }
177
178 static char *validate_params(const game_params *params, int full)
179 {
180     if (params->w <= 0 || params->h <= 0)
181         return "Width and height must both be greater than zero";
182     return NULL;
183 }
184
185 /* ----------------------------------------------------------------------
186  * Puzzle generation code.
187  * 
188  * For this particular puzzle, it seemed important to me to ensure
189  * a unique solution. I do this the brute-force way, by having a
190  * solver algorithm alongside the generator, and repeatedly
191  * generating a random grid until I find one whose solution is
192  * unique. It turns out that this isn't too onerous on a modern PC
193  * provided you keep grid size below around 30. Any offers of
194  * better algorithms, however, will be very gratefully received.
195  * 
196  * Another annoyance of this approach is that it limits the
197  * available puzzles to those solvable by the algorithm I've used.
198  * My algorithm only ever considers a single row or column at any
199  * one time, which means it's incapable of solving the following
200  * difficult example (found by Bella Image around 1995/6, when she
201  * and I were both doing maths degrees):
202  * 
203  *        2  1  2  1 
204  *
205  *      +--+--+--+--+
206  * 1 1  |  |  |  |  |
207  *      +--+--+--+--+
208  *   2  |  |  |  |  |
209  *      +--+--+--+--+
210  *   1  |  |  |  |  |
211  *      +--+--+--+--+
212  *   1  |  |  |  |  |
213  *      +--+--+--+--+
214  * 
215  * Obviously this cannot be solved by a one-row-or-column-at-a-time
216  * algorithm (it would require at least one row or column reading
217  * `2 1', `1 2', `3' or `4' to get started). However, it can be
218  * proved to have a unique solution: if the top left square were
219  * empty, then the only option for the top row would be to fill the
220  * two squares in the 1 columns, which would imply the squares
221  * below those were empty, leaving no place for the 2 in the second
222  * row. Contradiction. Hence the top left square is full, and the
223  * unique solution follows easily from that starting point.
224  * 
225  * (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
226  * it's useful to anyone.)
227  */
228
229 #ifndef STANDALONE_PICTURE_GENERATOR
230 static int float_compare(const void *av, const void *bv)
231 {
232     const float *a = (const float *)av;
233     const float *b = (const float *)bv;
234     if (*a < *b)
235         return -1;
236     else if (*a > *b)
237         return +1;
238     else
239         return 0;
240 }
241
242 static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
243 {
244     float *fgrid;
245     float *fgrid2;
246     int step, i, j;
247     float threshold;
248
249     fgrid = snewn(w*h, float);
250
251     for (i = 0; i < h; i++) {
252         for (j = 0; j < w; j++) {
253             fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
254         }
255     }
256
257     /*
258      * The above gives a completely random splattering of black and
259      * white cells. We want to gently bias this in favour of _some_
260      * reasonably thick areas of white and black, while retaining
261      * some randomness and fine detail.
262      * 
263      * So we evolve the starting grid using a cellular automaton.
264      * Currently, I'm doing something very simple indeed, which is
265      * to set each square to the average of the surrounding nine
266      * cells (or the average of fewer, if we're on a corner).
267      */
268     for (step = 0; step < 1; step++) {
269         fgrid2 = snewn(w*h, float);
270
271         for (i = 0; i < h; i++) {
272             for (j = 0; j < w; j++) {
273                 float sx, xbar;
274                 int n, p, q;
275
276                 /*
277                  * Compute the average of the surrounding cells.
278                  */
279                 n = 0;
280                 sx = 0.F;
281                 for (p = -1; p <= +1; p++) {
282                     for (q = -1; q <= +1; q++) {
283                         if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
284                             continue;
285                         /*
286                          * An additional special case not mentioned
287                          * above: if a grid dimension is 2xn then
288                          * we do not average across that dimension
289                          * at all. Otherwise a 2x2 grid would
290                          * contain four identical squares.
291                          */
292                         if ((h==2 && p!=0) || (w==2 && q!=0))
293                             continue;
294                         n++;
295                         sx += fgrid[(i+p)*w+(j+q)];
296                     }
297                 }
298                 xbar = sx / n;
299
300                 fgrid2[i*w+j] = xbar;
301             }
302         }
303
304         sfree(fgrid);
305         fgrid = fgrid2;
306     }
307
308     fgrid2 = snewn(w*h, float);
309     memcpy(fgrid2, fgrid, w*h*sizeof(float));
310     qsort(fgrid2, w*h, sizeof(float), float_compare);
311     threshold = fgrid2[w*h/2];
312     sfree(fgrid2);
313
314     for (i = 0; i < h; i++) {
315         for (j = 0; j < w; j++) {
316             retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
317                               GRID_EMPTY);
318         }
319     }
320
321     sfree(fgrid);
322 }
323 #endif
324
325 static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
326 {
327     int i, n;
328
329     n = 0;
330
331     for (i = 0; i < len; i++) {
332         if (start[i*step] == GRID_FULL) {
333             int runlen = 1;
334             while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
335                 runlen++;
336             ret[n++] = runlen;
337             i += runlen;
338         }
339
340         if (i < len && start[i*step] == GRID_UNKNOWN)
341             return -1;
342     }
343
344     return n;
345 }
346
347 #define UNKNOWN 0
348 #define BLOCK 1
349 #define DOT 2
350 #define STILL_UNKNOWN 3
351
352 #ifdef STANDALONE_SOLVER
353 int verbose = FALSE;
354 #endif
355
356 static int do_recurse(unsigned char *known, unsigned char *deduced,
357                        unsigned char *row,
358                        unsigned char *minpos_done, unsigned char *maxpos_done,
359                        unsigned char *minpos_ok, unsigned char *maxpos_ok,
360                        int *data, int len,
361                        int freespace, int ndone, int lowest)
362 {
363     int i, j, k;
364
365
366     /* This algorithm basically tries all possible ways the given rows of
367      * black blocks can be laid out in the row/column being examined.
368      * Special care is taken to avoid checking the tail of a row/column
369      * if the same conditions have already been checked during this recursion
370      * The algorithm also takes care to cut its losses as soon as an
371      * invalid (partial) solution is detected.
372      */
373     if (data[ndone]) {
374         if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
375             if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
376                 for (i=0; i<lowest; i++)
377                     deduced[i] |= row[i];
378             }
379             return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
380         } else {
381             if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
382             if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
383         }
384         for (i=0; i<=freespace; i++) {
385             j = lowest;
386             for (k=0; k<i; k++) {
387                 if (known[j] == BLOCK) goto next_iter;
388                 row[j++] = DOT;
389             }
390             for (k=0; k<data[ndone]; k++) {
391                 if (known[j] == DOT) goto next_iter;
392                 row[j++] = BLOCK;
393             }
394             if (j < len) {
395                 if (known[j] == BLOCK) goto next_iter;
396                 row[j++] = DOT;
397             }
398             if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
399                            minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
400                 if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
401                 if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
402                 if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
403             }
404             next_iter:
405             j++;
406         }
407         return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
408     } else {
409         for (i=lowest; i<len; i++) {
410             if (known[i] == BLOCK) return FALSE;
411             row[i] = DOT;
412             }
413         for (i=0; i<len; i++)
414             deduced[i] |= row[i];
415         return TRUE;
416     }
417 }
418
419
420 static int do_row(unsigned char *known, unsigned char *deduced,
421                   unsigned char *row,
422                   unsigned char *minpos_done, unsigned char *maxpos_done,
423                   unsigned char *minpos_ok, unsigned char *maxpos_ok,
424                   unsigned char *start, int len, int step, int *data,
425                   unsigned int *changed
426 #ifdef STANDALONE_SOLVER
427                   , const char *rowcol, int index, int cluewid
428 #endif
429                   )
430 {
431     int rowlen, i, freespace, done_any;
432
433     freespace = len+1;
434     for (rowlen = 0; data[rowlen]; rowlen++) {
435         minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
436         maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
437         freespace -= data[rowlen]+1;
438     }
439
440     for (i = 0; i < len; i++) {
441         known[i] = start[i*step];
442         deduced[i] = 0;
443     }
444     for (i = len - 1; i >= 0 && known[i] == DOT; i--)
445         freespace--;
446
447     if (rowlen == 0) {
448         memset(deduced, DOT, len);
449     } else if (rowlen == 1 && data[0] == len) {
450         memset(deduced, BLOCK, len);
451     } else {
452         do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok,
453                    maxpos_ok, data, len, freespace, 0, 0);
454     }
455
456     done_any = FALSE;
457     for (i=0; i<len; i++)
458         if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
459             start[i*step] = deduced[i];
460             if (changed) changed[i]++;
461             done_any = TRUE;
462         }
463 #ifdef STANDALONE_SOLVER
464     if (verbose && done_any) {
465         char buf[80];
466         int thiscluewid;
467         printf("%s %2d: [", rowcol, index);
468         for (thiscluewid = -1, i = 0; data[i]; i++)
469             thiscluewid += sprintf(buf, " %d", data[i]);
470         printf("%*s", cluewid - thiscluewid, "");
471         for (i = 0; data[i]; i++)
472             printf(" %d", data[i]);
473         printf(" ] ");
474         for (i = 0; i < len; i++)
475             putchar(known[i] == BLOCK ? '#' :
476                     known[i] == DOT ? '.' : '?');
477         printf(" -> ");
478         for (i = 0; i < len; i++)
479             putchar(start[i*step] == BLOCK ? '#' :
480                     start[i*step] == DOT ? '.' : '?');
481         putchar('\n');
482     }
483 #endif
484     return done_any;
485 }
486
487 static int solve_puzzle(const game_state *state, unsigned char *grid,
488                         int w, int h,
489                         unsigned char *matrix, unsigned char *workspace,
490                         unsigned int *changed_h, unsigned int *changed_w,
491                         int *rowdata
492 #ifdef STANDALONE_SOLVER
493                         , int cluewid
494 #else
495                         , int dummy
496 #endif
497                         )
498 {
499     int i, j, ok, max;
500     int max_h, max_w;
501
502     assert((state!=NULL && state->common->rowdata!=NULL) ^ (grid!=NULL));
503
504     max = max(w, h);
505
506     memset(matrix, 0, w*h);
507     if (state) {
508         for (i=0; i<w*h; i++) {
509             if (state->common->immutable[i])
510                 matrix[i] = state->grid[i];
511         }
512     }
513
514     /* For each column, compute how many squares can be deduced
515      * from just the row-data and initial clues.
516      * Later, changed_* will hold how many squares were changed
517      * in every row/column in the previous iteration
518      * Changed_* is used to choose the next rows / cols to re-examine
519      */
520     for (i=0; i<h; i++) {
521         int freespace, rowlen;
522         if (state && state->common->rowdata) {
523             memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
524             rowlen = state->common->rowlen[w+i];
525         } else {
526             rowlen = compute_rowdata(rowdata, grid+i*w, w, 1);
527         }
528         rowdata[rowlen] = 0;
529         if (rowlen == 0) {
530             changed_h[i] = w;
531         } else {
532             for (j=0, freespace=w+1; rowdata[j]; j++)
533                 freespace -= rowdata[j] + 1;
534             for (j=0, changed_h[i]=0; rowdata[j]; j++)
535                 if (rowdata[j] > freespace)
536                     changed_h[i] += rowdata[j] - freespace;
537         }
538         for (j = 0; j < w; j++)
539             if (matrix[i*w+j])
540                 changed_h[i]++;
541     }
542     for (i=0,max_h=0; i<h; i++)
543         if (changed_h[i] > max_h)
544             max_h = changed_h[i];
545     for (i=0; i<w; i++) {
546         int freespace, rowlen;
547         if (state && state->common->rowdata) {
548             memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
549             rowlen = state->common->rowlen[i];
550         } else {
551             rowlen = compute_rowdata(rowdata, grid+i, h, w);
552         }
553         rowdata[rowlen] = 0;
554         if (rowlen == 0) {
555             changed_w[i] = h;
556         } else {
557             for (j=0, freespace=h+1; rowdata[j]; j++)
558                 freespace -= rowdata[j] + 1;
559             for (j=0, changed_w[i]=0; rowdata[j]; j++)
560                 if (rowdata[j] > freespace)
561                     changed_w[i] += rowdata[j] - freespace;
562         }
563         for (j = 0; j < h; j++)
564             if (matrix[j*w+i])
565                 changed_w[i]++;
566     }
567     for (i=0,max_w=0; i<w; i++)
568         if (changed_w[i] > max_w)
569             max_w = changed_w[i];
570
571     /* Solve the puzzle.
572      * Process rows/columns individually. Deductions involving more than one
573      * row and/or column at a time are not supported.
574      * Take care to only process rows/columns which have been changed since they
575      * were previously processed.
576      * Also, prioritize rows/columns which have had the most changes since their
577      * previous processing, as they promise the greatest benefit.
578      * Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
579      */
580     do {
581         for (; max_h && max_h >= max_w; max_h--) {
582             for (i=0; i<h; i++) {
583                 if (changed_h[i] >= max_h) {
584                     if (state && state->common->rowdata) {
585                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
586                         rowdata[state->common->rowlen[w+i]] = 0;
587                     } else {
588                         rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
589                     }
590                     do_row(workspace, workspace+max, workspace+2*max,
591                            workspace+3*max, workspace+4*max,
592                            workspace+5*max, workspace+6*max,
593                            matrix+i*w, w, 1, rowdata, changed_w
594 #ifdef STANDALONE_SOLVER
595                            , "row", i+1, cluewid
596 #endif
597                            );
598                     changed_h[i] = 0;
599                 }
600             }
601             for (i=0,max_w=0; i<w; i++)
602                 if (changed_w[i] > max_w)
603                     max_w = changed_w[i];
604         }
605         for (; max_w && max_w >= max_h; max_w--) {
606             for (i=0; i<w; i++) {
607                 if (changed_w[i] >= max_w) {
608                     if (state && state->common->rowdata) {
609                         memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
610                         rowdata[state->common->rowlen[i]] = 0;
611                     } else {
612                         rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
613                     }
614                     do_row(workspace, workspace+max, workspace+2*max,
615                            workspace+3*max, workspace+4*max,
616                            workspace+5*max, workspace+6*max,
617                            matrix+i, h, w, rowdata, changed_h
618 #ifdef STANDALONE_SOLVER
619                            , "col", i+1, cluewid
620 #endif
621                            );
622                     changed_w[i] = 0;
623                 }
624             }
625             for (i=0,max_h=0; i<h; i++)
626                 if (changed_h[i] > max_h)
627                     max_h = changed_h[i];
628         }
629     } while (max_h>0 || max_w>0);
630
631     ok = TRUE;
632     for (i=0; i<h; i++) {
633         for (j=0; j<w; j++) {
634             if (matrix[i*w+j] == UNKNOWN)
635                 ok = FALSE;
636         }
637     }
638
639     return ok;
640 }
641
642 #ifndef STANDALONE_PICTURE_GENERATOR
643 static unsigned char *generate_soluble(random_state *rs, int w, int h)
644 {
645     int i, j, ok, ntries, max;
646     unsigned char *grid, *matrix, *workspace;
647     unsigned int *changed_h, *changed_w;
648     int *rowdata;
649
650     max = max(w, h);
651
652     grid = snewn(w*h, unsigned char);
653     /* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
654     matrix = snewn(w*h, unsigned char);
655     workspace = snewn(max*7, unsigned char);
656     changed_h = snewn(max+1, unsigned int);
657     changed_w = snewn(max+1, unsigned int);
658     rowdata = snewn(max+1, int);
659
660     ntries = 0;
661
662     do {
663         ntries++;
664
665         generate(rs, w, h, grid);
666
667         /*
668          * The game is a bit too easy if any row or column is
669          * completely black or completely white. An exception is
670          * made for rows/columns that are under 3 squares,
671          * otherwise nothing will ever be successfully generated.
672          */
673         ok = TRUE;
674         if (w > 2) {
675             for (i = 0; i < h; i++) {
676                 int colours = 0;
677                 for (j = 0; j < w; j++)
678                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
679                 if (colours != 3)
680                     ok = FALSE;
681             }
682         }
683         if (h > 2) {
684             for (j = 0; j < w; j++) {
685                 int colours = 0;
686                 for (i = 0; i < h; i++)
687                     colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
688                 if (colours != 3)
689                     ok = FALSE;
690             }
691         }
692         if (!ok)
693             continue;
694
695         ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
696                           changed_h, changed_w, rowdata, 0);
697     } while (!ok);
698
699     sfree(matrix);
700     sfree(workspace);
701     sfree(changed_h);
702     sfree(changed_w);
703     sfree(rowdata);
704     return grid;
705 }
706 #endif
707
708 #ifdef STANDALONE_PICTURE_GENERATOR
709 unsigned char *picture;
710 #endif
711
712 static char *new_game_desc(const game_params *params, random_state *rs,
713                            char **aux, int interactive)
714 {
715     unsigned char *grid;
716     int i, j, max, rowlen, *rowdata;
717     char intbuf[80], *desc;
718     int desclen, descpos;
719 #ifdef STANDALONE_PICTURE_GENERATOR
720     game_state *state;
721     int *index;
722 #endif
723
724     max = max(params->w, params->h);
725
726 #ifdef STANDALONE_PICTURE_GENERATOR
727     /*
728      * Fixed input picture.
729      */
730     grid = snewn(params->w * params->h, unsigned char);
731     memcpy(grid, picture, params->w * params->h);
732
733     /*
734      * Now winnow the immutable square set as far as possible.
735      */
736     state = snew(game_state);
737     state->grid = grid;
738     state->common = snew(game_state_common);
739     state->common->rowdata = NULL;
740     state->common->immutable = snewn(params->w * params->h, unsigned char);
741     memset(state->common->immutable, 1, params->w * params->h);
742
743     index = snewn(params->w * params->h, int);
744     for (i = 0; i < params->w * params->h; i++)
745         index[i] = i;
746     shuffle(index, params->w * params->h, sizeof(*index), rs);
747
748     {
749         unsigned char *matrix = snewn(params->w*params->h, unsigned char);
750         unsigned char *workspace = snewn(max*7, unsigned char);
751         unsigned int *changed_h = snewn(max+1, unsigned int);
752         unsigned int *changed_w = snewn(max+1, unsigned int);
753         int *rowdata = snewn(max+1, int);
754         for (i = 0; i < params->w * params->h; i++) {
755             state->common->immutable[index[i]] = 0;
756             if (!solve_puzzle(state, grid, params->w, params->h,
757                               matrix, workspace, changed_h, changed_w,
758                               rowdata, 0))
759                 state->common->immutable[index[i]] = 1;
760         }
761         sfree(workspace);
762         sfree(changed_h);
763         sfree(changed_w);
764         sfree(rowdata);
765         sfree(matrix);
766     }
767 #else
768     grid = generate_soluble(rs, params->w, params->h);
769 #endif
770     rowdata = snewn(max, int);
771
772     /*
773      * Save the solved game in aux.
774      */
775     if (aux) {
776         char *ai = snewn(params->w * params->h + 2, char);
777
778         /*
779          * String format is exactly the same as a solve move, so we
780          * can just dupstr this in solve_game().
781          */
782
783         ai[0] = 'S';
784
785         for (i = 0; i < params->w * params->h; i++)
786             ai[i+1] = grid[i] ? '1' : '0';
787
788         ai[params->w * params->h + 1] = '\0';
789
790         *aux = ai;
791     }
792
793     /*
794      * Seed is a slash-separated list of row contents; each row
795      * contents section is a dot-separated list of integers. Row
796      * contents are listed in the order (columns left to right,
797      * then rows top to bottom).
798      * 
799      * Simplest way to handle memory allocation is to make two
800      * passes, first computing the seed size and then writing it
801      * out.
802      */
803     desclen = 0;
804     for (i = 0; i < params->w + params->h; i++) {
805         if (i < params->w)
806             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
807         else
808             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
809                                      params->w, 1);
810         if (rowlen > 0) {
811             for (j = 0; j < rowlen; j++) {
812                 desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
813             }
814         } else {
815             desclen++;
816         }
817     }
818     desc = snewn(desclen, char);
819     descpos = 0;
820     for (i = 0; i < params->w + params->h; i++) {
821         if (i < params->w)
822             rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
823         else
824             rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
825                                      params->w, 1);
826         if (rowlen > 0) {
827             for (j = 0; j < rowlen; j++) {
828                 int len = sprintf(desc+descpos, "%d", rowdata[j]);
829                 if (j+1 < rowlen)
830                     desc[descpos + len] = '.';
831                 else
832                     desc[descpos + len] = '/';
833                 descpos += len+1;
834             }
835         } else {
836             desc[descpos++] = '/';
837         }
838     }
839     assert(descpos == desclen);
840     assert(desc[desclen-1] == '/');
841     desc[desclen-1] = '\0';
842 #ifdef STANDALONE_PICTURE_GENERATOR
843     for (i = 0; i < params->w * params->h; i++)
844         if (state->common->immutable[i])
845             break;
846     if (i < params->w * params->h) {
847         /*
848          * At least one immutable square, so we need a suffix.
849          */
850         int run;
851
852         desc = sresize(desc, desclen + params->w * params->h + 3, char);
853         desc[descpos-1] = ',';
854
855         run = 0;
856         for (i = 0; i < params->w * params->h; i++) {
857             if (!state->common->immutable[i]) {
858                 run++;
859                 if (run == 25) {
860                     desc[descpos++] = 'z';
861                     run = 0;
862                 }
863             } else {
864                 desc[descpos++] = run + (grid[i] == GRID_FULL ? 'A' : 'a');
865                 run = 0;
866             }
867         }
868         if (run > 0)
869             desc[descpos++] = run + 'a';
870         desc[descpos] = '\0';
871     }
872     sfree(state->common->immutable);
873     sfree(state->common);
874     sfree(state);
875 #endif
876     sfree(rowdata);
877     sfree(grid);
878     return desc;
879 }
880
881 static char *validate_desc(const game_params *params, const char *desc)
882 {
883     int i, n, rowspace;
884     const char *p;
885
886     for (i = 0; i < params->w + params->h; i++) {
887         if (i < params->w)
888             rowspace = params->h + 1;
889         else
890             rowspace = params->w + 1;
891
892         if (*desc && isdigit((unsigned char)*desc)) {
893             do {
894                 p = desc;
895                 while (*desc && isdigit((unsigned char)*desc)) desc++;
896                 n = atoi(p);
897                 rowspace -= n+1;
898
899                 if (rowspace < 0) {
900                     if (i < params->w)
901                         return "at least one column contains more numbers than will fit";
902                     else
903                         return "at least one row contains more numbers than will fit";
904                 }
905             } while (*desc++ == '.');
906         } else {
907             desc++;                    /* expect a slash immediately */
908         }
909
910         if (desc[-1] == '/') {
911             if (i+1 == params->w + params->h)
912                 return "too many row/column specifications";
913         } else if (desc[-1] == '\0' || desc[-1] == ',') {
914             if (i+1 < params->w + params->h)
915                 return "too few row/column specifications";
916         } else
917             return "unrecognised character in game specification";
918     }
919
920     if (desc[-1] == ',') {
921         /*
922          * Optional extra piece of game description which fills in
923          * some grid squares as extra clues.
924          */
925         i = 0;
926         while (i < params->w * params->h) {
927             int c = (unsigned char)*desc++;
928             if ((c >= 'a' && c <= 'z') ||
929                 (c >= 'A' && c <= 'Z')) {
930                 int len = tolower(c) - 'a';
931                 i += len;
932                 if (len < 25 && i < params->w*params->h)
933                     i++;
934                 if (i > params->w * params->h) {
935                     return "too much data in clue-squares section";
936                 }
937             } else if (!c) {
938                 return "too little data in clue-squares section";
939             } else {
940                 return "unrecognised character in clue-squares section";
941             }
942         }
943         if (*desc) {
944             return "too much data in clue-squares section";
945         }
946     }
947
948     return NULL;
949 }
950
951 static game_state *new_game(midend *me, const game_params *params,
952                             const char *desc)
953 {
954     int i;
955     const char *p;
956     game_state *state = snew(game_state);
957
958     state->common = snew(game_state_common);
959     state->common->refcount = 1;
960
961     state->common->w = params->w;
962     state->common->h = params->h;
963
964     state->grid = snewn(state->common->w * state->common->h, unsigned char);
965     memset(state->grid, GRID_UNKNOWN, state->common->w * state->common->h);
966
967     state->common->immutable = snewn(state->common->w * state->common->h,
968                                      unsigned char);
969     memset(state->common->immutable, 0, state->common->w * state->common->h);
970
971     state->common->rowsize = max(state->common->w, state->common->h);
972     state->common->rowdata = snewn(state->common->rowsize * (state->common->w + state->common->h), int);
973     state->common->rowlen = snewn(state->common->w + state->common->h, int);
974
975     state->completed = state->cheated = FALSE;
976
977     for (i = 0; i < params->w + params->h; i++) {
978         state->common->rowlen[i] = 0;
979         if (*desc && isdigit((unsigned char)*desc)) {
980             do {
981                 p = desc;
982                 while (*desc && isdigit((unsigned char)*desc)) desc++;
983                 state->common->rowdata[state->common->rowsize * i + state->common->rowlen[i]++] =
984                     atoi(p);
985             } while (*desc++ == '.');
986         } else {
987             desc++;                    /* expect a slash immediately */
988         }
989     }
990
991     if (desc[-1] == ',') {
992         /*
993          * Optional extra piece of game description which fills in
994          * some grid squares as extra clues.
995          */
996         i = 0;
997         while (i < params->w * params->h) {
998             int c = (unsigned char)*desc++;
999             int full = isupper(c), len = tolower(c) - 'a';
1000             i += len;
1001             if (len < 25 && i < params->w*params->h) {
1002                 state->grid[i] = full ? GRID_FULL : GRID_EMPTY;
1003                 state->common->immutable[i] = TRUE;
1004                 i++;
1005             }
1006         }
1007     }
1008
1009     return state;
1010 }
1011
1012 static game_state *dup_game(const game_state *state)
1013 {
1014     game_state *ret = snew(game_state);
1015
1016     ret->common = state->common;
1017     ret->common->refcount++;
1018
1019     ret->grid = snewn(ret->common->w * ret->common->h, unsigned char);
1020     memcpy(ret->grid, state->grid, ret->common->w * ret->common->h);
1021
1022     ret->completed = state->completed;
1023     ret->cheated = state->cheated;
1024
1025     return ret;
1026 }
1027
1028 static void free_game(game_state *state)
1029 {
1030     if (--state->common->refcount == 0) {
1031         sfree(state->common->rowdata);
1032         sfree(state->common->rowlen);
1033         sfree(state->common->immutable);
1034         sfree(state->common);
1035     }
1036     sfree(state->grid);
1037     sfree(state);
1038 }
1039
1040 static char *solve_game(const game_state *state, const game_state *currstate,
1041                         const char *ai, char **error)
1042 {
1043     unsigned char *matrix;
1044     int w = state->common->w, h = state->common->h;
1045     int i;
1046     char *ret;
1047     int max, ok;
1048     unsigned char *workspace;
1049     unsigned int *changed_h, *changed_w;
1050     int *rowdata;
1051
1052     /*
1053      * If we already have the solved state in ai, copy it out.
1054      */
1055     if (ai)
1056         return dupstr(ai);
1057
1058     max = max(w, h);
1059     matrix = snewn(w*h, unsigned char);
1060     workspace = snewn(max*7, unsigned char);
1061     changed_h = snewn(max+1, unsigned int);
1062     changed_w = snewn(max+1, unsigned int);
1063     rowdata = snewn(max+1, int);
1064
1065     ok = solve_puzzle(state, NULL, w, h, matrix, workspace,
1066                       changed_h, changed_w, rowdata, 0);
1067
1068     sfree(workspace);
1069     sfree(changed_h);
1070     sfree(changed_w);
1071     sfree(rowdata);
1072
1073     if (!ok) {
1074         sfree(matrix);
1075         *error = "Solving algorithm cannot complete this puzzle";
1076         return NULL;
1077     }
1078
1079     ret = snewn(w*h+2, char);
1080     ret[0] = 'S';
1081     for (i = 0; i < w*h; i++) {
1082         assert(matrix[i] == BLOCK || matrix[i] == DOT);
1083         ret[i+1] = (matrix[i] == BLOCK ? '1' : '0');
1084     }
1085     ret[w*h+1] = '\0';
1086
1087     sfree(matrix);
1088
1089     return ret;
1090 }
1091
1092 static int game_can_format_as_text_now(const game_params *params)
1093 {
1094     return TRUE;
1095 }
1096
1097 static char *game_text_format(const game_state *state)
1098 {
1099     int w = state->common->w, h = state->common->h, i, j;
1100     int left_gap = 0, top_gap = 0, ch = 2, cw = 1, limit = 1;
1101
1102     int len, topleft, lw, lh, gw, gh; /* {line,grid}_{width,height} */
1103     char *board, *buf;
1104
1105     for (i = 0; i < w; ++i) {
1106         top_gap = max(top_gap, state->common->rowlen[i]);
1107         for (j = 0; j < state->common->rowlen[i]; ++j)
1108             while (state->common->rowdata[i*state->common->rowsize + j] >= limit) {
1109                 ++cw;
1110                 limit *= 10;
1111             }
1112     }
1113     for (i = 0; i < h; ++i) {
1114         int rowlen = 0, predecessors = FALSE;
1115         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1116             int copy = state->common->rowdata[(i+w)*state->common->rowsize + j];
1117             rowlen += predecessors;
1118             predecessors = TRUE;
1119             do ++rowlen; while (copy /= 10);
1120         }
1121         left_gap = max(left_gap, rowlen);
1122     }
1123
1124     cw = max(cw, 3);
1125
1126     gw = w*cw + 2;
1127     gh = h*ch + 1;
1128     lw = gw + left_gap;
1129     lh = gh + top_gap;
1130     len = lw * lh;
1131     topleft = lw * top_gap + left_gap;
1132
1133     board = snewn(len + 1, char);
1134     sprintf(board, "%*s\n", len - 2, "");
1135
1136     for (i = 0; i < lh; ++i) {
1137         board[lw - 1 + i*lw] = '\n';
1138         if (i < top_gap) continue;
1139         board[lw - 2 + i*lw] = ((i - top_gap) % ch ? '|' : '+');
1140     }
1141
1142     for (i = 0; i < w; ++i) {
1143         for (j = 0; j < state->common->rowlen[i]; ++j) {
1144             int cell = topleft + i*cw + 1 + lw*(j - state->common->rowlen[i]);
1145             int nch = sprintf(board + cell, "%*d", cw - 1,
1146                               state->common->rowdata[i*state->common->rowsize + j]);
1147             board[cell + nch] = ' '; /* de-NUL-ify */
1148         }
1149     }
1150
1151     buf = snewn(left_gap, char);
1152     for (i = 0; i < h; ++i) {
1153         char *p = buf, *start = board + top_gap*lw + left_gap + (i*ch+1)*lw;
1154         for (j = 0; j < state->common->rowlen[i+w]; ++j) {
1155             if (p > buf) *p++ = ' ';
1156             p += sprintf(p, "%d", state->common->rowdata[(i+w)*state->common->rowsize + j]);
1157         }
1158         memcpy(start - (p - buf), buf, p - buf);
1159     }
1160
1161     for (i = 0; i < w; ++i) {
1162         for (j = 0; j < h; ++j) {
1163             int cell = topleft + i*cw + j*ch*lw;
1164             int center = cell + cw/2 + (ch/2)*lw;
1165             int dx, dy;
1166             board[cell] = 0 ? center : '+';
1167             for (dx = 1; dx < cw; ++dx) board[cell + dx] = '-';
1168             for (dy = 1; dy < ch; ++dy) board[cell + dy*lw] = '|';
1169             if (state->grid[i*w+j] == GRID_UNKNOWN) continue;
1170             for (dx = 1; dx < cw; ++dx)
1171                 for (dy = 1; dy < ch; ++dy)
1172                     board[cell + dx + dy*lw] =
1173                         state->grid[i*w+j] == GRID_FULL ? '#' : '.';
1174         }
1175     }
1176
1177     memcpy(board + topleft + h*ch*lw, board + topleft, gw - 1);
1178
1179     sfree(buf);
1180
1181     return board;
1182 }
1183
1184 struct game_ui {
1185     int dragging;
1186     int drag_start_x;
1187     int drag_start_y;
1188     int drag_end_x;
1189     int drag_end_y;
1190     int drag, release, state;
1191     int cur_x, cur_y, cur_visible;
1192 };
1193
1194 static game_ui *new_ui(const game_state *state)
1195 {
1196     game_ui *ret;
1197
1198     ret = snew(game_ui);
1199     ret->dragging = FALSE;
1200     ret->cur_x = ret->cur_y = ret->cur_visible = 0;
1201
1202     return ret;
1203 }
1204
1205 static void free_ui(game_ui *ui)
1206 {
1207     sfree(ui);
1208 }
1209
1210 static char *encode_ui(const game_ui *ui)
1211 {
1212     return NULL;
1213 }
1214
1215 static void decode_ui(game_ui *ui, const char *encoding)
1216 {
1217 }
1218
1219 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1220                                const game_state *newstate)
1221 {
1222 }
1223
1224 struct game_drawstate {
1225     int started;
1226     int w, h;
1227     int tilesize;
1228     unsigned char *visible, *numcolours;
1229     int cur_x, cur_y;
1230 };
1231
1232 static char *interpret_move(const game_state *state, game_ui *ui,
1233                             const game_drawstate *ds,
1234                             int x, int y, int button)
1235 {
1236     int control = button & MOD_CTRL, shift = button & MOD_SHFT;
1237     button &= ~MOD_MASK;
1238
1239     x = FROMCOORD(state->common->w, x);
1240     y = FROMCOORD(state->common->h, y);
1241
1242     if (x >= 0 && x < state->common->w && y >= 0 && y < state->common->h &&
1243         (button == LEFT_BUTTON || button == RIGHT_BUTTON ||
1244          button == MIDDLE_BUTTON)) {
1245 #ifdef STYLUS_BASED
1246         int currstate = state->grid[y * state->common->w + x];
1247 #endif
1248
1249         ui->dragging = TRUE;
1250
1251         if (button == LEFT_BUTTON) {
1252             ui->drag = LEFT_DRAG;
1253             ui->release = LEFT_RELEASE;
1254 #ifdef STYLUS_BASED
1255             ui->state = (currstate + 2) % 3; /* FULL -> EMPTY -> UNKNOWN */
1256 #else
1257             ui->state = GRID_FULL;
1258 #endif
1259         } else if (button == RIGHT_BUTTON) {
1260             ui->drag = RIGHT_DRAG;
1261             ui->release = RIGHT_RELEASE;
1262 #ifdef STYLUS_BASED
1263             ui->state = (currstate + 1) % 3; /* EMPTY -> FULL -> UNKNOWN */
1264 #else
1265             ui->state = GRID_EMPTY;
1266 #endif
1267         } else /* if (button == MIDDLE_BUTTON) */ {
1268             ui->drag = MIDDLE_DRAG;
1269             ui->release = MIDDLE_RELEASE;
1270             ui->state = GRID_UNKNOWN;
1271         }
1272
1273         ui->drag_start_x = ui->drag_end_x = x;
1274         ui->drag_start_y = ui->drag_end_y = y;
1275         ui->cur_visible = 0;
1276
1277         return "";                     /* UI activity occurred */
1278     }
1279
1280     if (ui->dragging && button == ui->drag) {
1281         /*
1282          * There doesn't seem much point in allowing a rectangle
1283          * drag; people will generally only want to drag a single
1284          * horizontal or vertical line, so we make that easy by
1285          * snapping to it.
1286          * 
1287          * Exception: if we're _middle_-button dragging to tag
1288          * things as UNKNOWN, we may well want to trash an entire
1289          * area and start over!
1290          */
1291         if (ui->state != GRID_UNKNOWN) {
1292             if (abs(x - ui->drag_start_x) > abs(y - ui->drag_start_y))
1293                 y = ui->drag_start_y;
1294             else
1295                 x = ui->drag_start_x;
1296         }
1297
1298         if (x < 0) x = 0;
1299         if (y < 0) y = 0;
1300         if (x >= state->common->w) x = state->common->w - 1;
1301         if (y >= state->common->h) y = state->common->h - 1;
1302
1303         ui->drag_end_x = x;
1304         ui->drag_end_y = y;
1305
1306         return "";                     /* UI activity occurred */
1307     }
1308
1309     if (ui->dragging && button == ui->release) {
1310         int x1, x2, y1, y2, xx, yy;
1311         int move_needed = FALSE;
1312
1313         x1 = min(ui->drag_start_x, ui->drag_end_x);
1314         x2 = max(ui->drag_start_x, ui->drag_end_x);
1315         y1 = min(ui->drag_start_y, ui->drag_end_y);
1316         y2 = max(ui->drag_start_y, ui->drag_end_y);
1317
1318         for (yy = y1; yy <= y2; yy++)
1319             for (xx = x1; xx <= x2; xx++)
1320                 if (!state->common->immutable[yy * state->common->w + xx] &&
1321                     state->grid[yy * state->common->w + xx] != ui->state)
1322                     move_needed = TRUE;
1323
1324         ui->dragging = FALSE;
1325
1326         if (move_needed) {
1327             char buf[80];
1328             sprintf(buf, "%c%d,%d,%d,%d",
1329                     (char)(ui->state == GRID_FULL ? 'F' :
1330                            ui->state == GRID_EMPTY ? 'E' : 'U'),
1331                     x1, y1, x2-x1+1, y2-y1+1);
1332             return dupstr(buf);
1333         } else
1334             return "";                 /* UI activity occurred */
1335     }
1336
1337     if (IS_CURSOR_MOVE(button)) {
1338         int x = ui->cur_x, y = ui->cur_y, newstate;
1339         char buf[80];
1340         move_cursor(button, &ui->cur_x, &ui->cur_y, state->common->w, state->common->h, 0);
1341         ui->cur_visible = 1;
1342         if (!control && !shift) return "";
1343
1344         newstate = control ? shift ? GRID_UNKNOWN : GRID_FULL : GRID_EMPTY;
1345         if (state->grid[y * state->common->w + x] == newstate &&
1346             state->grid[ui->cur_y * state->common->w + ui->cur_x] == newstate)
1347             return "";
1348
1349         sprintf(buf, "%c%d,%d,%d,%d", control ? shift ? 'U' : 'F' : 'E',
1350                 min(x, ui->cur_x), min(y, ui->cur_y),
1351                 abs(x - ui->cur_x) + 1, abs(y - ui->cur_y) + 1);
1352         return dupstr(buf);
1353     }
1354
1355     if (IS_CURSOR_SELECT(button)) {
1356         int currstate = state->grid[ui->cur_y * state->common->w + ui->cur_x];
1357         int newstate;
1358         char buf[80];
1359
1360         if (!ui->cur_visible) {
1361             ui->cur_visible = 1;
1362             return "";
1363         }
1364
1365         if (button == CURSOR_SELECT2)
1366             newstate = currstate == GRID_UNKNOWN ? GRID_EMPTY :
1367                 currstate == GRID_EMPTY ? GRID_FULL : GRID_UNKNOWN;
1368         else
1369             newstate = currstate == GRID_UNKNOWN ? GRID_FULL :
1370                 currstate == GRID_FULL ? GRID_EMPTY : GRID_UNKNOWN;
1371
1372         sprintf(buf, "%c%d,%d,%d,%d",
1373                 (char)(newstate == GRID_FULL ? 'F' :
1374                        newstate == GRID_EMPTY ? 'E' : 'U'),
1375                 ui->cur_x, ui->cur_y, 1, 1);
1376         return dupstr(buf);
1377     }
1378
1379     return NULL;
1380 }
1381
1382 static game_state *execute_move(const game_state *from, const char *move)
1383 {
1384     game_state *ret;
1385     int x1, x2, y1, y2, xx, yy;
1386     int val;
1387
1388     if (move[0] == 'S' &&
1389         strlen(move) == from->common->w * from->common->h + 1) {
1390         int i;
1391
1392         ret = dup_game(from);
1393
1394         for (i = 0; i < ret->common->w * ret->common->h; i++)
1395             ret->grid[i] = (move[i+1] == '1' ? GRID_FULL : GRID_EMPTY);
1396
1397         ret->completed = ret->cheated = TRUE;
1398
1399         return ret;
1400     } else if ((move[0] == 'F' || move[0] == 'E' || move[0] == 'U') &&
1401         sscanf(move+1, "%d,%d,%d,%d", &x1, &y1, &x2, &y2) == 4 &&
1402         x1 >= 0 && x2 >= 0 && x1+x2 <= from->common->w &&
1403         y1 >= 0 && y2 >= 0 && y1+y2 <= from->common->h) {
1404
1405         x2 += x1;
1406         y2 += y1;
1407         val = (move[0] == 'F' ? GRID_FULL :
1408                  move[0] == 'E' ? GRID_EMPTY : GRID_UNKNOWN);
1409
1410         ret = dup_game(from);
1411         for (yy = y1; yy < y2; yy++)
1412             for (xx = x1; xx < x2; xx++)
1413                 if (!ret->common->immutable[yy * ret->common->w + xx])
1414                     ret->grid[yy * ret->common->w + xx] = val;
1415
1416         /*
1417          * An actual change, so check to see if we've completed the
1418          * game.
1419          */
1420         if (!ret->completed) {
1421             int *rowdata = snewn(ret->common->rowsize, int);
1422             int i, len;
1423
1424             ret->completed = TRUE;
1425
1426             for (i=0; i<ret->common->w; i++) {
1427                 len = compute_rowdata(rowdata, ret->grid+i,
1428                                       ret->common->h, ret->common->w);
1429                 if (len != ret->common->rowlen[i] ||
1430                     memcmp(ret->common->rowdata+i*ret->common->rowsize,
1431                            rowdata, len * sizeof(int))) {
1432                     ret->completed = FALSE;
1433                     break;
1434                 }
1435             }
1436             for (i=0; i<ret->common->h; i++) {
1437                 len = compute_rowdata(rowdata, ret->grid+i*ret->common->w,
1438                                       ret->common->w, 1);
1439                 if (len != ret->common->rowlen[i+ret->common->w] ||
1440                     memcmp(ret->common->rowdata +
1441                            (i+ret->common->w)*ret->common->rowsize,
1442                            rowdata, len * sizeof(int))) {
1443                     ret->completed = FALSE;
1444                     break;
1445                 }
1446             }
1447
1448             sfree(rowdata);
1449         }
1450
1451         return ret;
1452     } else
1453         return NULL;
1454 }
1455
1456 /* ----------------------------------------------------------------------
1457  * Error-checking during gameplay.
1458  */
1459
1460 /*
1461  * The difficulty in error-checking Pattern is to make the error check
1462  * _weak_ enough. The most obvious way would be to check each row and
1463  * column by calling (a modified form of) do_row() to recursively
1464  * analyse the row contents against the clue set and see if the
1465  * GRID_UNKNOWNs could be filled in in any way that would end up
1466  * correct. However, this turns out to be such a strong error check as
1467  * to constitute a spoiler in many situations: you make a typo while
1468  * trying to fill in one row, and not only does the row light up to
1469  * indicate an error, but several columns crossed by the move also
1470  * light up and draw your attention to deductions you hadn't even
1471  * noticed you could make.
1472  *
1473  * So instead I restrict error-checking to 'complete runs' within a
1474  * row, by which I mean contiguous sequences of GRID_FULL bounded at
1475  * both ends by either GRID_EMPTY or the ends of the row. We identify
1476  * all the complete runs in a row, and verify that _those_ are
1477  * consistent with the row's clue list. Sequences of complete runs
1478  * separated by solid GRID_EMPTY are required to match contiguous
1479  * sequences in the clue list, whereas if there's at least one
1480  * GRID_UNKNOWN between any two complete runs then those two need not
1481  * be contiguous in the clue list.
1482  *
1483  * To simplify the edge cases, I pretend that the clue list for the
1484  * row is extended with a 0 at each end, and I also pretend that the
1485  * grid data for the row is extended with a GRID_EMPTY and a
1486  * zero-length run at each end. This permits the contiguity checker to
1487  * handle the fiddly end effects (e.g. if the first contiguous
1488  * sequence of complete runs in the grid matches _something_ in the
1489  * clue list but not at the beginning, this is allowable iff there's a
1490  * GRID_UNKNOWN before the first one) with minimal faff, since the end
1491  * effects just drop out as special cases of the normal inter-run
1492  * handling (in this code the above case is not 'at the end of the
1493  * clue list' at all, but between the implicit initial zero run and
1494  * the first nonzero one).
1495  *
1496  * We must also be a little careful about how we search for a
1497  * contiguous sequence of runs. In the clue list (1 1 2 1 2 3),
1498  * suppose we see a GRID_UNKNOWN and then a length-1 run. We search
1499  * for 1 in the clue list and find it at the very beginning. But now
1500  * suppose we find a length-2 run with no GRID_UNKNOWN before it. We
1501  * can't naively look at the next clue from the 1 we found, because
1502  * that'll be the second 1 and won't match. Instead, we must backtrack
1503  * by observing that the 2 we've just found must be contiguous with
1504  * the 1 we've already seen, so we search for the sequence (1 2) and
1505  * find it starting at the second 1. Now if we see a 3, we must
1506  * rethink again and search for (1 2 3).
1507  */
1508
1509 struct errcheck_state {
1510     /*
1511      * rowdata and rowlen point at the clue data for this row in the
1512      * game state.
1513      */
1514     int *rowdata;
1515     int rowlen;
1516     /*
1517      * rowpos indicates the lowest position where it would be valid to
1518      * see our next run length. It might be equal to rowlen,
1519      * indicating that the next run would have to be the terminating 0.
1520      */
1521     int rowpos;
1522     /*
1523      * ncontig indicates how many runs we've seen in a contiguous
1524      * block. This is taken into account when searching for the next
1525      * run we find, unless ncontig is zeroed out first by encountering
1526      * a GRID_UNKNOWN.
1527      */
1528     int ncontig;
1529 };
1530
1531 static int errcheck_found_run(struct errcheck_state *es, int r)
1532 {
1533 /* Macro to handle the pretence that rowdata has a 0 at each end */
1534 #define ROWDATA(k) ((k)<0 || (k)>=es->rowlen ? 0 : es->rowdata[(k)])
1535
1536     /*
1537      * See if we can find this new run length at a position where it
1538      * also matches the last 'ncontig' runs we've seen.
1539      */
1540     int i, newpos;
1541     for (newpos = es->rowpos; newpos <= es->rowlen; newpos++) {
1542
1543         if (ROWDATA(newpos) != r)
1544             goto notfound;
1545
1546         for (i = 1; i <= es->ncontig; i++)
1547             if (ROWDATA(newpos - i) != ROWDATA(es->rowpos - i))
1548                 goto notfound;
1549
1550         es->rowpos = newpos+1;
1551         es->ncontig++;
1552         return TRUE;
1553
1554       notfound:;
1555     }
1556
1557     return FALSE;
1558
1559 #undef ROWDATA
1560 }
1561
1562 static int check_errors(const game_state *state, int i)
1563 {
1564     int start, step, end, j;
1565     int val, runlen;
1566     struct errcheck_state aes, *es = &aes;
1567
1568     es->rowlen = state->common->rowlen[i];
1569     es->rowdata = state->common->rowdata + state->common->rowsize * i;
1570     /* Pretend that we've already encountered the initial zero run */
1571     es->ncontig = 1;
1572     es->rowpos = 0;
1573
1574     if (i < state->common->w) {
1575         start = i;
1576         step = state->common->w;
1577         end = start + step * state->common->h;
1578     } else {
1579         start = (i - state->common->w) * state->common->w;
1580         step = 1;
1581         end = start + step * state->common->w;
1582     }
1583
1584     runlen = -1;
1585     for (j = start - step; j <= end; j += step) {
1586         if (j < start || j == end)
1587             val = GRID_EMPTY;
1588         else
1589             val = state->grid[j];
1590
1591         if (val == GRID_UNKNOWN) {
1592             runlen = -1;
1593             es->ncontig = 0;
1594         } else if (val == GRID_FULL) {
1595             if (runlen >= 0)
1596                 runlen++;
1597         } else if (val == GRID_EMPTY) {
1598             if (runlen > 0) {
1599                 if (!errcheck_found_run(es, runlen))
1600                     return TRUE;       /* error! */
1601             }
1602             runlen = 0;
1603         }
1604     }
1605
1606     /* Signal end-of-row by sending errcheck_found_run the terminating
1607      * zero run, which will be marked as contiguous with the previous
1608      * run if and only if there hasn't been a GRID_UNKNOWN before. */
1609     if (!errcheck_found_run(es, 0))
1610         return TRUE;                   /* error at the last minute! */
1611
1612     return FALSE;                      /* no error */
1613 }
1614
1615 /* ----------------------------------------------------------------------
1616  * Drawing routines.
1617  */
1618
1619 static void game_compute_size(const game_params *params, int tilesize,
1620                               int *x, int *y)
1621 {
1622     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1623     struct { int tilesize; } ads, *ds = &ads;
1624     ads.tilesize = tilesize;
1625
1626     *x = SIZE(params->w);
1627     *y = SIZE(params->h);
1628 }
1629
1630 static void game_set_size(drawing *dr, game_drawstate *ds,
1631                           const game_params *params, int tilesize)
1632 {
1633     ds->tilesize = tilesize;
1634 }
1635
1636 static float *game_colours(frontend *fe, int *ncolours)
1637 {
1638     float *ret = snewn(3 * NCOLOURS, float);
1639     int i;
1640
1641     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1642
1643     for (i = 0; i < 3; i++) {
1644         ret[COL_GRID    * 3 + i] = 0.3F;
1645         ret[COL_UNKNOWN * 3 + i] = 0.5F;
1646         ret[COL_TEXT    * 3 + i] = 0.0F;
1647         ret[COL_FULL    * 3 + i] = 0.0F;
1648         ret[COL_EMPTY   * 3 + i] = 1.0F;
1649     }
1650     ret[COL_CURSOR * 3 + 0] = 1.0F;
1651     ret[COL_CURSOR * 3 + 1] = 0.25F;
1652     ret[COL_CURSOR * 3 + 2] = 0.25F;
1653     ret[COL_ERROR * 3 + 0] = 1.0F;
1654     ret[COL_ERROR * 3 + 1] = 0.0F;
1655     ret[COL_ERROR * 3 + 2] = 0.0F;
1656
1657     *ncolours = NCOLOURS;
1658     return ret;
1659 }
1660
1661 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1662 {
1663     struct game_drawstate *ds = snew(struct game_drawstate);
1664
1665     ds->started = FALSE;
1666     ds->w = state->common->w;
1667     ds->h = state->common->h;
1668     ds->visible = snewn(ds->w * ds->h, unsigned char);
1669     ds->tilesize = 0;                  /* not decided yet */
1670     memset(ds->visible, 255, ds->w * ds->h);
1671     ds->numcolours = snewn(ds->w + ds->h, unsigned char);
1672     memset(ds->numcolours, 255, ds->w + ds->h);
1673     ds->cur_x = ds->cur_y = 0;
1674
1675     return ds;
1676 }
1677
1678 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1679 {
1680     sfree(ds->visible);
1681     sfree(ds);
1682 }
1683
1684 static void grid_square(drawing *dr, game_drawstate *ds,
1685                         int y, int x, int state, int cur)
1686 {
1687     int xl, xr, yt, yb, dx, dy, dw, dh;
1688
1689     draw_rect(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1690               TILE_SIZE, TILE_SIZE, COL_GRID);
1691
1692     xl = (x % 5 == 0 ? 1 : 0);
1693     yt = (y % 5 == 0 ? 1 : 0);
1694     xr = (x % 5 == 4 || x == ds->w-1 ? 1 : 0);
1695     yb = (y % 5 == 4 || y == ds->h-1 ? 1 : 0);
1696
1697     dx = TOCOORD(ds->w, x) + 1 + xl;
1698     dy = TOCOORD(ds->h, y) + 1 + yt;
1699     dw = TILE_SIZE - xl - xr - 1;
1700     dh = TILE_SIZE - yt - yb - 1;
1701
1702     draw_rect(dr, dx, dy, dw, dh,
1703               (state == GRID_FULL ? COL_FULL :
1704                state == GRID_EMPTY ? COL_EMPTY : COL_UNKNOWN));
1705     if (cur) {
1706         draw_rect_outline(dr, dx, dy, dw, dh, COL_CURSOR);
1707         draw_rect_outline(dr, dx+1, dy+1, dw-2, dh-2, COL_CURSOR);
1708     }
1709
1710     draw_update(dr, TOCOORD(ds->w, x), TOCOORD(ds->h, y),
1711                 TILE_SIZE, TILE_SIZE);
1712 }
1713
1714 /*
1715  * Draw the numbers for a single row or column.
1716  */
1717 static void draw_numbers(drawing *dr, game_drawstate *ds,
1718                          const game_state *state, int i, int erase, int colour)
1719 {
1720     int rowlen = state->common->rowlen[i];
1721     int *rowdata = state->common->rowdata + state->common->rowsize * i;
1722     int nfit;
1723     int j;
1724
1725     if (erase) {
1726         if (i < state->common->w) {
1727             draw_rect(dr, TOCOORD(state->common->w, i), 0,
1728                       TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE,
1729                       COL_BACKGROUND);
1730         } else {
1731             draw_rect(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1732                       BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE,
1733                       COL_BACKGROUND);
1734         }
1735     }
1736
1737     /*
1738      * Normally I space the numbers out by the same distance as the
1739      * tile size. However, if there are more numbers than available
1740      * spaces, I have to squash them up a bit.
1741      */
1742     if (i < state->common->w)
1743         nfit = TLBORDER(state->common->h);
1744     else
1745         nfit = TLBORDER(state->common->w);
1746     nfit = max(rowlen, nfit) - 1;
1747     assert(nfit > 0);
1748
1749     for (j = 0; j < rowlen; j++) {
1750         int x, y;
1751         char str[80];
1752
1753         if (i < state->common->w) {
1754             x = TOCOORD(state->common->w, i);
1755             y = BORDER + TILE_SIZE * (TLBORDER(state->common->h)-1);
1756             y -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->h)-1) / nfit;
1757         } else {
1758             y = TOCOORD(state->common->h, i - state->common->w);
1759             x = BORDER + TILE_SIZE * (TLBORDER(state->common->w)-1);
1760             x -= ((rowlen-j-1)*TILE_SIZE) * (TLBORDER(state->common->w)-1) / nfit;
1761         }
1762
1763         sprintf(str, "%d", rowdata[j]);
1764         draw_text(dr, x+TILE_SIZE/2, y+TILE_SIZE/2, FONT_VARIABLE,
1765                   TILE_SIZE/2, ALIGN_HCENTRE | ALIGN_VCENTRE, colour, str);
1766     }
1767
1768     if (i < state->common->w) {
1769         draw_update(dr, TOCOORD(state->common->w, i), 0,
1770                     TILE_SIZE, BORDER + TLBORDER(state->common->h) * TILE_SIZE);
1771     } else {
1772         draw_update(dr, 0, TOCOORD(state->common->h, i - state->common->w),
1773                     BORDER + TLBORDER(state->common->w) * TILE_SIZE, TILE_SIZE);
1774     }
1775 }
1776
1777 static void game_redraw(drawing *dr, game_drawstate *ds,
1778                         const game_state *oldstate, const game_state *state,
1779                         int dir, const game_ui *ui,
1780                         float animtime, float flashtime)
1781 {
1782     int i, j;
1783     int x1, x2, y1, y2;
1784     int cx, cy, cmoved;
1785
1786     if (!ds->started) {
1787         /*
1788          * The initial contents of the window are not guaranteed
1789          * and can vary with front ends. To be on the safe side,
1790          * all games should start by drawing a big background-
1791          * colour rectangle covering the whole window.
1792          */
1793         draw_rect(dr, 0, 0, SIZE(ds->w), SIZE(ds->h), COL_BACKGROUND);
1794
1795         /*
1796          * Draw the grid outline.
1797          */
1798         draw_rect(dr, TOCOORD(ds->w, 0) - 1, TOCOORD(ds->h, 0) - 1,
1799                   ds->w * TILE_SIZE + 3, ds->h * TILE_SIZE + 3,
1800                   COL_GRID);
1801
1802         ds->started = TRUE;
1803
1804         draw_update(dr, 0, 0, SIZE(ds->w), SIZE(ds->h));
1805     }
1806
1807     if (ui->dragging) {
1808         x1 = min(ui->drag_start_x, ui->drag_end_x);
1809         x2 = max(ui->drag_start_x, ui->drag_end_x);
1810         y1 = min(ui->drag_start_y, ui->drag_end_y);
1811         y2 = max(ui->drag_start_y, ui->drag_end_y);
1812     } else {
1813         x1 = x2 = y1 = y2 = -1;        /* placate gcc warnings */
1814     }
1815
1816     if (ui->cur_visible) {
1817         cx = ui->cur_x; cy = ui->cur_y;
1818     } else {
1819         cx = cy = -1;
1820     }
1821     cmoved = (cx != ds->cur_x || cy != ds->cur_y);
1822
1823     /*
1824      * Now draw any grid squares which have changed since last
1825      * redraw.
1826      */
1827     for (i = 0; i < ds->h; i++) {
1828         for (j = 0; j < ds->w; j++) {
1829             int val, cc = 0;
1830
1831             /*
1832              * Work out what state this square should be drawn in,
1833              * taking any current drag operation into account.
1834              */
1835             if (ui->dragging && x1 <= j && j <= x2 && y1 <= i && i <= y2 &&
1836                 !state->common->immutable[i * state->common->w + j])
1837                 val = ui->state;
1838             else
1839                 val = state->grid[i * state->common->w + j];
1840
1841             if (cmoved) {
1842                 /* the cursor has moved; if we were the old or
1843                  * the new cursor position we need to redraw. */
1844                 if (j == cx && i == cy) cc = 1;
1845                 if (j == ds->cur_x && i == ds->cur_y) cc = 1;
1846             }
1847
1848             /*
1849              * Briefly invert everything twice during a completion
1850              * flash.
1851              */
1852             if (flashtime > 0 &&
1853                 (flashtime <= FLASH_TIME/3 || flashtime >= FLASH_TIME*2/3) &&
1854                 val != GRID_UNKNOWN)
1855                 val = (GRID_FULL ^ GRID_EMPTY) ^ val;
1856
1857             if (ds->visible[i * ds->w + j] != val || cc) {
1858                 grid_square(dr, ds, i, j, val,
1859                             (j == cx && i == cy));
1860                 ds->visible[i * ds->w + j] = val;
1861             }
1862         }
1863     }
1864     ds->cur_x = cx; ds->cur_y = cy;
1865
1866     /*
1867      * Redraw any numbers which have changed their colour due to error
1868      * indication.
1869      */
1870     for (i = 0; i < state->common->w + state->common->h; i++) {
1871         int colour = check_errors(state, i) ? COL_ERROR : COL_TEXT;
1872         if (ds->numcolours[i] != colour) {
1873             draw_numbers(dr, ds, state, i, TRUE, colour);
1874             ds->numcolours[i] = colour;
1875         }
1876     }
1877 }
1878
1879 static float game_anim_length(const game_state *oldstate,
1880                               const game_state *newstate, int dir, game_ui *ui)
1881 {
1882     return 0.0F;
1883 }
1884
1885 static float game_flash_length(const game_state *oldstate,
1886                                const game_state *newstate, int dir, game_ui *ui)
1887 {
1888     if (!oldstate->completed && newstate->completed &&
1889         !oldstate->cheated && !newstate->cheated)
1890         return FLASH_TIME;
1891     return 0.0F;
1892 }
1893
1894 static int game_status(const game_state *state)
1895 {
1896     return state->completed ? +1 : 0;
1897 }
1898
1899 static int game_timing_state(const game_state *state, game_ui *ui)
1900 {
1901     return TRUE;
1902 }
1903
1904 static void game_print_size(const game_params *params, float *x, float *y)
1905 {
1906     int pw, ph;
1907
1908     /*
1909      * I'll use 5mm squares by default.
1910      */
1911     game_compute_size(params, 500, &pw, &ph);
1912     *x = pw / 100.0F;
1913     *y = ph / 100.0F;
1914 }
1915
1916 static void game_print(drawing *dr, const game_state *state, int tilesize)
1917 {
1918     int w = state->common->w, h = state->common->h;
1919     int ink = print_mono_colour(dr, 0);
1920     int x, y, i;
1921
1922     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1923     game_drawstate ads, *ds = &ads;
1924     game_set_size(dr, ds, NULL, tilesize);
1925
1926     /*
1927      * Border.
1928      */
1929     print_line_width(dr, TILE_SIZE / 16);
1930     draw_rect_outline(dr, TOCOORD(w, 0), TOCOORD(h, 0),
1931                       w*TILE_SIZE, h*TILE_SIZE, ink);
1932
1933     /*
1934      * Grid.
1935      */
1936     for (x = 1; x < w; x++) {
1937         print_line_width(dr, TILE_SIZE / (x % 5 ? 128 : 24));
1938         draw_line(dr, TOCOORD(w, x), TOCOORD(h, 0),
1939                   TOCOORD(w, x), TOCOORD(h, h), ink);
1940     }
1941     for (y = 1; y < h; y++) {
1942         print_line_width(dr, TILE_SIZE / (y % 5 ? 128 : 24));
1943         draw_line(dr, TOCOORD(w, 0), TOCOORD(h, y),
1944                   TOCOORD(w, w), TOCOORD(h, y), ink);
1945     }
1946
1947     /*
1948      * Clues.
1949      */
1950     for (i = 0; i < state->common->w + state->common->h; i++)
1951         draw_numbers(dr, ds, state, i, FALSE, ink);
1952
1953     /*
1954      * Solution.
1955      */
1956     print_line_width(dr, TILE_SIZE / 128);
1957     for (y = 0; y < h; y++)
1958         for (x = 0; x < w; x++) {
1959             if (state->grid[y*w+x] == GRID_FULL)
1960                 draw_rect(dr, TOCOORD(w, x), TOCOORD(h, y),
1961                           TILE_SIZE, TILE_SIZE, ink);
1962             else if (state->grid[y*w+x] == GRID_EMPTY)
1963                 draw_circle(dr, TOCOORD(w, x) + TILE_SIZE/2,
1964                             TOCOORD(h, y) + TILE_SIZE/2,
1965                             TILE_SIZE/12, ink, ink);
1966         }
1967 }
1968
1969 #ifdef COMBINED
1970 #define thegame pattern
1971 #endif
1972
1973 const struct game thegame = {
1974     "Pattern", "games.pattern", "pattern",
1975     default_params,
1976     game_fetch_preset, NULL,
1977     decode_params,
1978     encode_params,
1979     free_params,
1980     dup_params,
1981     TRUE, game_configure, custom_params,
1982     validate_params,
1983     new_game_desc,
1984     validate_desc,
1985     new_game,
1986     dup_game,
1987     free_game,
1988     TRUE, solve_game,
1989     TRUE, game_can_format_as_text_now, game_text_format,
1990     new_ui,
1991     free_ui,
1992     encode_ui,
1993     decode_ui,
1994     game_changed_state,
1995     interpret_move,
1996     execute_move,
1997     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1998     game_colours,
1999     game_new_drawstate,
2000     game_free_drawstate,
2001     game_redraw,
2002     game_anim_length,
2003     game_flash_length,
2004     game_status,
2005     TRUE, FALSE, game_print_size, game_print,
2006     FALSE,                             /* wants_statusbar */
2007     FALSE, game_timing_state,
2008     REQUIRE_RBUTTON,                   /* flags */
2009 };
2010
2011 #ifdef STANDALONE_SOLVER
2012
2013 int main(int argc, char **argv)
2014 {
2015     game_params *p;
2016     game_state *s;
2017     char *id = NULL, *desc, *err;
2018
2019     while (--argc > 0) {
2020         char *p = *++argv;
2021         if (*p == '-') {
2022             if (!strcmp(p, "-v")) {
2023                 verbose = TRUE;
2024             } else {
2025                 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2026                 return 1;
2027             }
2028         } else {
2029             id = p;
2030         }
2031     }
2032
2033     if (!id) {
2034         fprintf(stderr, "usage: %s <game_id>\n", argv[0]);
2035         return 1;
2036     }
2037
2038     desc = strchr(id, ':');
2039     if (!desc) {
2040         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2041         return 1;
2042     }
2043     *desc++ = '\0';
2044
2045     p = default_params();
2046     decode_params(p, id);
2047     err = validate_desc(p, desc);
2048     if (err) {
2049         fprintf(stderr, "%s: %s\n", argv[0], err);
2050         return 1;
2051     }
2052     s = new_game(NULL, p, desc);
2053
2054     {
2055         int w = p->w, h = p->h, i, j, max, cluewid = 0;
2056         unsigned char *matrix, *workspace;
2057         unsigned int *changed_h, *changed_w;
2058         int *rowdata;
2059
2060         matrix = snewn(w*h, unsigned char);
2061         max = max(w, h);
2062         workspace = snewn(max*7, unsigned char);
2063         changed_h = snewn(max+1, unsigned int);
2064         changed_w = snewn(max+1, unsigned int);
2065         rowdata = snewn(max+1, int);
2066
2067         if (verbose) {
2068             int thiswid;
2069             /*
2070              * Work out the maximum text width of the clue numbers
2071              * in a row or column, so we can print the solver's
2072              * working in a nicely lined up way.
2073              */
2074             for (i = 0; i < (w+h); i++) {
2075                 char buf[80];
2076                 for (thiswid = -1, j = 0; j < s->common->rowlen[i]; j++)
2077                     thiswid += sprintf
2078                         (buf, " %d",
2079                          s->common->rowdata[s->common->rowsize*i+j]);
2080                 if (cluewid < thiswid)
2081                     cluewid = thiswid;
2082             }
2083         }
2084
2085         solve_puzzle(s, NULL, w, h, matrix, workspace,
2086                      changed_h, changed_w, rowdata, cluewid);
2087
2088         for (i = 0; i < h; i++) {
2089             for (j = 0; j < w; j++) {
2090                 int c = (matrix[i*w+j] == UNKNOWN ? '?' :
2091                          matrix[i*w+j] == BLOCK ? '#' :
2092                          matrix[i*w+j] == DOT ? '.' :
2093                          '!');
2094                 putchar(c);
2095             }
2096             printf("\n");
2097         }
2098     }
2099
2100     return 0;
2101 }
2102
2103 #endif
2104
2105 #ifdef STANDALONE_PICTURE_GENERATOR
2106
2107 /*
2108  * Main program for the standalone picture generator. To use it,
2109  * simply provide it with an XBM-format bitmap file (note XBM, not
2110  * XPM) on standard input, and it will output a game ID in return.
2111  * For example:
2112  *
2113  *   $ ./patternpicture < calligraphic-A.xbm
2114  *   15x15:2/4/2/2/2/3/3/3.1/3.1/3.1/11/14/12/6/1/2/2/3/4/5/1.3/2.3/1.3/2.3/1.4/9/1.1.3/2.2.3/5.4/3.2
2115  *
2116  * That looks easy, of course - all the program has done is to count
2117  * up the clue numbers! But in fact, it's done more than that: it's
2118  * also checked that the result is uniquely soluble from just the
2119  * numbers. If it hadn't been, then it would have also left some
2120  * filled squares in the playing area as extra clues.
2121  *
2122  *   $ ./patternpicture < cube.xbm
2123  *   15x15:10/2.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.10/1.1.1/1.1.1/1.1.1/2.1/10/10/1.2/1.1.1/1.1.1/1.1.1/10.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.1.1/1.2/10,TNINzzzzGNzw
2124  *
2125  * This enables a reasonably convenient design workflow for coming up
2126  * with pictorial Pattern puzzles which _are_ uniquely soluble without
2127  * those inelegant pre-filled squares. Fire up a bitmap editor (X11
2128  * bitmap(1) is good enough), save a trial .xbm, and then test it by
2129  * running a command along the lines of
2130  *
2131  *   $ ./pattern $(./patternpicture < test.xbm)
2132  *
2133  * If the resulting window pops up with some pre-filled squares, then
2134  * that tells you which parts of the image are giving rise to
2135  * ambiguities, so try making tweaks in those areas, try the test
2136  * command again, and see if it helps. Once you have a design for
2137  * which the Pattern starting grid comes out empty, there's your game
2138  * ID.
2139  */
2140
2141 #include <time.h>
2142
2143 int main(int argc, char **argv)
2144 {
2145     game_params *par;
2146     char *params, *desc;
2147     random_state *rs;
2148     time_t seed = time(NULL);
2149     char buf[4096];
2150     int i;
2151     int x, y;
2152
2153     par = default_params();
2154     if (argc > 1)
2155         decode_params(par, argv[1]);   /* get difficulty */
2156     par->w = par->h = -1;
2157
2158     /*
2159      * Now read an XBM file from standard input. This is simple and
2160      * hacky and will do very little error detection, so don't feed
2161      * it bogus data.
2162      */
2163     picture = NULL;
2164     x = y = 0;
2165     while (fgets(buf, sizeof(buf), stdin)) {
2166         buf[strcspn(buf, "\r\n")] = '\0';
2167         if (!strncmp(buf, "#define", 7)) {
2168             /*
2169              * Lines starting `#define' give the width and height.
2170              */
2171             char *num = buf + strlen(buf);
2172             char *symend;
2173
2174             while (num > buf && isdigit((unsigned char)num[-1]))
2175                 num--;
2176             symend = num;
2177             while (symend > buf && isspace((unsigned char)symend[-1]))
2178                 symend--;
2179
2180             if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
2181                 par->w = atoi(num);
2182             else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
2183                 par->h = atoi(num);
2184         } else {
2185             /*
2186              * Otherwise, break the string up into words and take
2187              * any word of the form `0x' plus hex digits to be a
2188              * byte.
2189              */
2190             char *p, *wordstart;
2191
2192             if (!picture) {
2193                 if (par->w < 0 || par->h < 0) {
2194                     printf("failed to read width and height\n");
2195                     return 1;
2196                 }
2197                 picture = snewn(par->w * par->h, unsigned char);
2198                 for (i = 0; i < par->w * par->h; i++)
2199                     picture[i] = GRID_UNKNOWN;
2200             }
2201
2202             p = buf;
2203             while (*p) {
2204                 while (*p && (*p == ',' || isspace((unsigned char)*p)))
2205                     p++;
2206                 wordstart = p;
2207                 while (*p && !(*p == ',' || *p == '}' ||
2208                                isspace((unsigned char)*p)))
2209                     p++;
2210                 if (*p)
2211                     *p++ = '\0';
2212
2213                 if (wordstart[0] == '0' &&
2214                     (wordstart[1] == 'x' || wordstart[1] == 'X') &&
2215                     !wordstart[2 + strspn(wordstart+2,
2216                                           "0123456789abcdefABCDEF")]) {
2217                     unsigned long byte = strtoul(wordstart+2, NULL, 16);
2218                     for (i = 0; i < 8; i++) {
2219                         int bit = (byte >> i) & 1;
2220                         if (y < par->h && x < par->w)
2221                             picture[y * par->w + x] =
2222                                 bit ? GRID_FULL : GRID_EMPTY;
2223                         x++;
2224                     }
2225
2226                     if (x >= par->w) {
2227                         x = 0;
2228                         y++;
2229                     }
2230                 }
2231             }
2232         }
2233     }
2234
2235     for (i = 0; i < par->w * par->h; i++)
2236         if (picture[i] == GRID_UNKNOWN) {
2237             fprintf(stderr, "failed to read enough bitmap data\n");
2238             return 1;
2239         }
2240
2241     rs = random_new((void*)&seed, sizeof(time_t));
2242
2243     desc = new_game_desc(par, rs, NULL, FALSE);
2244     params = encode_params(par, FALSE);
2245     printf("%s:%s\n", params, desc);
2246
2247     sfree(desc);
2248     sfree(params);
2249     free_params(par);
2250     random_free(rs);
2251
2252     return 0;
2253 }
2254
2255 #endif
2256
2257 /* vim: set shiftwidth=4 tabstop=8: */