chiark / gitweb /
Use the game_state and space typedefs
[sgt-puzzles.git] / galaxies.c
1 /*
2  * galaxies.c: implementation of 'Tentai Show' from Nikoli,
3  *             also sometimes called 'Spiral Galaxies'.
4  *
5  * Notes:
6  *
7  * Grid is stored as size (2n-1), holding edges as well as spaces
8  * (and thus vertices too, at edge intersections).
9  *
10  * Any dot will thus be positioned at one of our grid points,
11  * which saves any faffing with half-of-a-square stuff.
12  *
13  * Edges have on/off state; obviously the actual edges of the
14  * board are fixed to on, and everything else starts as off.
15  *
16  * TTD:
17    * Cleverer solver
18    * Think about how to display remote groups of tiles?
19  *
20  * Bugs:
21  *
22  * Notable puzzle IDs:
23  *
24  * Nikoli's example [web site has wrong highlighting]
25  * (at http://www.nikoli.co.jp/en/puzzles/astronomical_show/):
26  *  5x5:eBbbMlaBbOEnf
27  *
28  * The 'spiral galaxies puzzles are NP-complete' paper
29  * (at http://www.stetson.edu/~efriedma/papers/spiral.pdf):
30  *  7x7:chpgdqqqoezdddki
31  *
32  * Puzzle competition pdf examples
33  * (at http://www.puzzleratings.org/Yurekli2006puz.pdf):
34  *  6x6:EDbaMucCohbrecEi
35  *  10x10:beFbufEEzowDlxldibMHezBQzCdcFzjlci
36  *  13x13:dCemIHFFkJajjgDfdbdBzdzEgjccoPOcztHjBczLDjczqktJjmpreivvNcggFi
37  *
38  */
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <assert.h>
44 #include <ctype.h>
45 #include <math.h>
46
47 #include "puzzles.h"
48
49 #ifdef DEBUGGING
50 #define solvep debug
51 #else
52 int solver_show_working;
53 #define solvep(x) do { if (solver_show_working) { printf x; } } while(0)
54 #endif
55
56 #ifdef STANDALONE_PICTURE_GENERATOR
57 /*
58  * Dirty hack to enable the generator to construct a game ID which
59  * solves to a specified black-and-white bitmap. We define a global
60  * variable here which gives the desired colour of each square, and
61  * we arrange that the grid generator never merges squares of
62  * different colours.
63  *
64  * The bitmap as stored here is a simple int array (at these sizes
65  * it isn't worth doing fiddly bit-packing). picture[y*w+x] is 1
66  * iff the pixel at (x,y) is intended to be black.
67  *
68  * (It might be nice to be able to specify some pixels as
69  * don't-care, to give the generator more leeway. But that might be
70  * fiddly.)
71  */
72 static int *picture;
73 #endif
74
75 enum {
76     COL_BACKGROUND,
77     COL_WHITEBG,
78     COL_BLACKBG,
79     COL_WHITEDOT,
80     COL_BLACKDOT,
81     COL_GRID,
82     COL_EDGE,
83     COL_ARROW,
84     COL_CURSOR,
85     NCOLOURS
86 };
87
88 #define DIFFLIST(A)             \
89     A(NORMAL,Normal,n)          \
90     A(UNREASONABLE,Unreasonable,u)
91
92 #define ENUM(upper,title,lower) DIFF_ ## upper,
93 #define TITLE(upper,title,lower) #title,
94 #define ENCODE(upper,title,lower) #lower
95 #define CONFIG(upper,title,lower) ":" #title
96 enum { DIFFLIST(ENUM)
97     DIFF_IMPOSSIBLE, DIFF_AMBIGUOUS, DIFF_UNFINISHED, DIFF_MAX };
98 static char const *const galaxies_diffnames[] = {
99     DIFFLIST(TITLE) "Impossible", "Ambiguous", "Unfinished" };
100 static char const galaxies_diffchars[] = DIFFLIST(ENCODE);
101 #define DIFFCONFIG DIFFLIST(CONFIG)
102
103 struct game_params {
104     /* X and Y is the area of the board as seen by
105      * the user, not the (2n+1) area the game uses. */
106     int w, h, diff;
107 };
108
109 enum { s_tile, s_edge, s_vertex };
110
111 #define F_DOT           1       /* there's a dot here */
112 #define F_EDGE_SET      2       /* the edge is set */
113 #define F_TILE_ASSOC    4       /* this tile is associated with a dot. */
114 #define F_DOT_BLACK     8       /* (ui only) dot is black. */
115 #define F_MARK          16      /* scratch flag */
116 #define F_REACHABLE     32
117 #define F_SCRATCH       64
118 #define F_MULTIPLE      128
119 #define F_DOT_HOLD      256
120 #define F_GOOD          512
121
122 typedef struct space {
123     int x, y;           /* its position */
124     int type;
125     unsigned int flags;
126     int dotx, doty;     /* if flags & F_TILE_ASSOC */
127     int nassoc;         /* if flags & F_DOT */
128 } space;
129
130 #define INGRID(s,x,y) ((x) >= 0 && (y) >= 0 &&                  \
131                        (x) < (state)->sx && (y) < (state)->sy)
132 #define INUI(s,x,y)   ((x) > 0 && (y) > 0 &&                  \
133                        (x) < ((state)->sx-1) && (y) < ((state)->sy-1))
134
135 #define GRID(s,g,x,y) ((s)->g[((y)*(s)->sx)+(x)])
136 #define SPACE(s,x,y) GRID(s,grid,x,y)
137
138 struct game_state {
139     int w, h;           /* size from params */
140     int sx, sy;         /* allocated size, (2x-1)*(2y-1) */
141     space *grid;
142     int completed, used_solve;
143     int ndots;
144     space **dots;
145
146     midend *me;         /* to call supersede_game_desc */
147     int cdiff;          /* difficulty of current puzzle (for status bar),
148                            or -1 if stale. */
149 };
150
151 /* ----------------------------------------------------------
152  * Game parameters and presets
153  */
154
155 /* make up some sensible default sizes */
156
157 #define DEFAULT_PRESET 0
158
159 static const game_params galaxies_presets[] = {
160     {  7,  7, DIFF_NORMAL },
161     {  7,  7, DIFF_UNREASONABLE },
162     { 10, 10, DIFF_NORMAL },
163     { 15, 15, DIFF_NORMAL },
164 };
165
166 static int game_fetch_preset(int i, char **name, game_params **params)
167 {
168     game_params *ret;
169     char buf[80];
170
171     if (i < 0 || i >= lenof(galaxies_presets))
172         return FALSE;
173
174     ret = snew(game_params);
175     *ret = galaxies_presets[i]; /* structure copy */
176
177     sprintf(buf, "%dx%d %s", ret->w, ret->h,
178             galaxies_diffnames[ret->diff]);
179
180     if (name) *name = dupstr(buf);
181     *params = ret;
182     return TRUE;
183 }
184
185 static game_params *default_params(void)
186 {
187     game_params *ret;
188     game_fetch_preset(DEFAULT_PRESET, NULL, &ret);
189     return ret;
190 }
191
192 static void free_params(game_params *params)
193 {
194     sfree(params);
195 }
196
197 static game_params *dup_params(const game_params *params)
198 {
199     game_params *ret = snew(game_params);
200     *ret = *params;                    /* structure copy */
201     return ret;
202 }
203
204 static void decode_params(game_params *params, char const *string)
205 {
206     params->h = params->w = atoi(string);
207     params->diff = DIFF_NORMAL;
208     while (*string && isdigit((unsigned char)*string)) string++;
209     if (*string == 'x') {
210         string++;
211         params->h = atoi(string);
212         while (*string && isdigit((unsigned char)*string)) string++;
213     }
214     if (*string == 'd') {
215         int i;
216         string++;
217         for (i = 0; i <= DIFF_UNREASONABLE; i++)
218             if (*string == galaxies_diffchars[i])
219                 params->diff = i;
220         if (*string) string++;
221     }
222 }
223
224 static char *encode_params(const game_params *params, int full)
225 {
226     char str[80];
227     sprintf(str, "%dx%d", params->w, params->h);
228     if (full)
229         sprintf(str + strlen(str), "d%c", galaxies_diffchars[params->diff]);
230     return dupstr(str);
231 }
232
233 static config_item *game_configure(const game_params *params)
234 {
235     config_item *ret;
236     char buf[80];
237
238     ret = snewn(4, config_item);
239
240     ret[0].name = "Width";
241     ret[0].type = C_STRING;
242     sprintf(buf, "%d", params->w);
243     ret[0].sval = dupstr(buf);
244     ret[0].ival = 0;
245
246     ret[1].name = "Height";
247     ret[1].type = C_STRING;
248     sprintf(buf, "%d", params->h);
249     ret[1].sval = dupstr(buf);
250     ret[1].ival = 0;
251
252     ret[2].name = "Difficulty";
253     ret[2].type = C_CHOICES;
254     ret[2].sval = DIFFCONFIG;
255     ret[2].ival = params->diff;
256
257     ret[3].name = NULL;
258     ret[3].type = C_END;
259     ret[3].sval = NULL;
260     ret[3].ival = 0;
261
262     return ret;
263 }
264
265 static game_params *custom_params(const config_item *cfg)
266 {
267     game_params *ret = snew(game_params);
268
269     ret->w = atoi(cfg[0].sval);
270     ret->h = atoi(cfg[1].sval);
271     ret->diff = cfg[2].ival;
272
273     return ret;
274 }
275
276 static char *validate_params(const game_params *params, int full)
277 {
278     if (params->w < 3 || params->h < 3)
279         return "Width and height must both be at least 3";
280     /*
281      * This shouldn't be able to happen at all, since decode_params
282      * and custom_params will never generate anything that isn't
283      * within range.
284      */
285     assert(params->diff <= DIFF_UNREASONABLE);
286
287     return NULL;
288 }
289
290 /* ----------------------------------------------------------
291  * Game utility functions.
292  */
293
294 static void add_dot(space *space) {
295     assert(!(space->flags & F_DOT));
296     space->flags |= F_DOT;
297     space->nassoc = 0;
298 }
299
300 static void remove_dot(space *space) {
301     assert(space->flags & F_DOT);
302     space->flags &= ~F_DOT;
303 }
304
305 static void remove_assoc(const game_state *state, space *tile) {
306     if (tile->flags & F_TILE_ASSOC) {
307         SPACE(state, tile->dotx, tile->doty).nassoc--;
308         tile->flags &= ~F_TILE_ASSOC;
309         tile->dotx = -1;
310         tile->doty = -1;
311     }
312 }
313
314 static void add_assoc(const game_state *state, space *tile, space *dot) {
315     remove_assoc(state, tile);
316
317 #ifdef STANDALONE_PICTURE_GENERATOR
318     if (picture)
319         assert(!picture[(tile->y/2) * state->w + (tile->x/2)] ==
320                !(dot->flags & F_DOT_BLACK));
321 #endif
322     tile->flags |= F_TILE_ASSOC;
323     tile->dotx = dot->x;
324     tile->doty = dot->y;
325     dot->nassoc++;
326     /*debug(("add_assoc sp %d %d --> dot %d,%d, new nassoc %d.\n",
327            tile->x, tile->y, dot->x, dot->y, dot->nassoc));*/
328 }
329
330 static space *sp2dot(const game_state *state, int x, int y)
331 {
332     space *sp = &SPACE(state, x, y);
333     if (!(sp->flags & F_TILE_ASSOC)) return NULL;
334     return &SPACE(state, sp->dotx, sp->doty);
335 }
336
337 #define IS_VERTICAL_EDGE(x) ((x % 2) == 0)
338
339 static int game_can_format_as_text_now(const game_params *params)
340 {
341     return TRUE;
342 }
343
344 static char *game_text_format(const game_state *state)
345 {
346     int maxlen = (state->sx+1)*state->sy, x, y;
347     char *ret, *p;
348     space *sp;
349
350     ret = snewn(maxlen+1, char);
351     p = ret;
352
353     for (y = 0; y < state->sy; y++) {
354         for (x = 0; x < state->sx; x++) {
355             sp = &SPACE(state, x, y);
356             if (sp->flags & F_DOT)
357                 *p++ = 'o';
358 #if 0
359             else if (sp->flags & (F_REACHABLE|F_MULTIPLE|F_MARK))
360                 *p++ = (sp->flags & F_MULTIPLE) ? 'M' :
361                     (sp->flags & F_REACHABLE) ? 'R' : 'X';
362 #endif
363             else {
364                 switch (sp->type) {
365                 case s_tile:
366                     if (sp->flags & F_TILE_ASSOC) {
367                         space *dot = sp2dot(state, sp->x, sp->y);
368                         if (dot && dot->flags & F_DOT)
369                             *p++ = (dot->flags & F_DOT_BLACK) ? 'B' : 'W';
370                         else
371                             *p++ = '?'; /* association with not-a-dot. */
372                     } else
373                         *p++ = ' ';
374                     break;
375
376                 case s_vertex:
377                     *p++ = '+';
378                     break;
379
380                 case s_edge:
381                     if (sp->flags & F_EDGE_SET)
382                         *p++ = (IS_VERTICAL_EDGE(x)) ? '|' : '-';
383                     else
384                         *p++ = ' ';
385                     break;
386
387                 default:
388                     assert(!"shouldn't get here!");
389                 }
390             }
391         }
392         *p++ = '\n';
393     }
394
395     assert(p - ret == maxlen);
396     *p = '\0';
397
398     return ret;
399 }
400
401 static void dbg_state(const game_state *state)
402 {
403 #ifdef DEBUGGING
404     char *temp = game_text_format(state);
405     debug(("%s\n", temp));
406     sfree(temp);
407 #endif
408 }
409
410 /* Space-enumeration callbacks should all return 1 for 'progress made',
411  * -1 for 'impossible', and 0 otherwise. */
412 typedef int (*space_cb)(game_state *state, space *sp, void *ctx);
413
414 #define IMPOSSIBLE_QUITS        1
415
416 static int foreach_sub(game_state *state, space_cb cb, unsigned int f,
417                        void *ctx, int startx, int starty)
418 {
419     int x, y, progress = 0, impossible = 0, ret;
420     space *sp;
421
422     for (y = starty; y < state->sy; y += 2) {
423         sp = &SPACE(state, startx, y);
424         for (x = startx; x < state->sx; x += 2) {
425             ret = cb(state, sp, ctx);
426             if (ret == -1) {
427                 if (f & IMPOSSIBLE_QUITS) return -1;
428                 impossible = -1;
429             } else if (ret == 1) {
430                 progress = 1;
431             }
432             sp += 2;
433         }
434     }
435     return impossible ? -1 : progress;
436 }
437
438 static int foreach_tile(game_state *state, space_cb cb, unsigned int f,
439                         void *ctx)
440 {
441     return foreach_sub(state, cb, f, ctx, 1, 1);
442 }
443
444 static int foreach_edge(game_state *state, space_cb cb, unsigned int f,
445                         void *ctx)
446 {
447     int ret1, ret2;
448
449     ret1 = foreach_sub(state, cb, f, ctx, 0, 1);
450     ret2 = foreach_sub(state, cb, f, ctx, 1, 0);
451
452     if (ret1 == -1 || ret2 == -1) return -1;
453     return (ret1 || ret2) ? 1 : 0;
454 }
455
456 #if 0
457 static int foreach_vertex(game_state *state, space_cb cb, unsigned int f,
458                           void *ctx)
459 {
460     return foreach_sub(state, cb, f, ctx, 0, 0);
461 }
462 #endif
463
464 #if 0
465 static int is_same_assoc(game_state *state,
466                          int x1, int y1, int x2, int y2)
467 {
468     space *s1, *s2;
469
470     if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2))
471         return 0;
472
473     s1 = &SPACE(state, x1, y1);
474     s2 = &SPACE(state, x2, y2);
475     assert(s1->type == s_tile && s2->type == s_tile);
476     if ((s1->flags & F_TILE_ASSOC) && (s2->flags & F_TILE_ASSOC) &&
477         s1->dotx == s2->dotx && s1->doty == s2->doty)
478         return 1;
479     return 0; /* 0 if not same or not both associated. */
480 }
481 #endif
482
483 #if 0
484 static int edges_into_vertex(game_state *state,
485                              int x, int y)
486 {
487     int dx, dy, nx, ny, count = 0;
488
489     assert(SPACE(state, x, y).type == s_vertex);
490     for (dx = -1; dx <= 1; dx++) {
491         for (dy = -1; dy <= 1; dy++) {
492             if (dx != 0 && dy != 0) continue;
493             if (dx == 0 && dy == 0) continue;
494
495             nx = x+dx; ny = y+dy;
496             if (!INGRID(state, nx, ny)) continue;
497             assert(SPACE(state, nx, ny).type == s_edge);
498             if (SPACE(state, nx, ny).flags & F_EDGE_SET)
499                 count++;
500         }
501     }
502     return count;
503 }
504 #endif
505
506 static space *space_opposite_dot(game_state *state, space *sp, space *dot)
507 {
508     int dx, dy, tx, ty;
509     space *sp2;
510
511     dx = sp->x - dot->x;
512     dy = sp->y - dot->y;
513     tx = dot->x - dx;
514     ty = dot->y - dy;
515     if (!INGRID(state, tx, ty)) return NULL;
516
517     sp2 = &SPACE(state, tx, ty);
518     assert(sp2->type == sp->type);
519     return sp2;
520 }
521
522 static space *tile_opposite(game_state *state, space *sp)
523 {
524     space *dot;
525
526     assert(sp->flags & F_TILE_ASSOC);
527     dot = &SPACE(state, sp->dotx, sp->doty);
528     return space_opposite_dot(state, sp, dot);
529 }
530
531 static int dotfortile(game_state *state, space *tile, space *dot)
532 {
533     space *tile_opp = space_opposite_dot(state, tile, dot);
534
535     if (!tile_opp) return 0; /* opposite would be off grid */
536     if (tile_opp->flags & F_TILE_ASSOC &&
537             (tile_opp->dotx != dot->x || tile_opp->doty != dot->y))
538             return 0; /* opposite already associated with diff. dot */
539     return 1;
540 }
541
542 static void adjacencies(game_state *state, space *sp, space **a1s, space **a2s)
543 {
544     int dxs[4] = {-1, 1, 0, 0}, dys[4] = {0, 0, -1, 1};
545     int n, x, y;
546
547     /* this function needs optimising. */
548
549     for (n = 0; n < 4; n++) {
550         x = sp->x+dxs[n];
551         y = sp->y+dys[n];
552
553         if (INGRID(state, x, y)) {
554             a1s[n] = &SPACE(state, x, y);
555
556             x += dxs[n]; y += dys[n];
557
558             if (INGRID(state, x, y))
559                 a2s[n] = &SPACE(state, x, y);
560             else
561                 a2s[n] = NULL;
562         } else {
563             a1s[n] = a2s[n] = NULL;
564         }
565     }
566 }
567
568 static int outline_tile_fordot(game_state *state, space *tile, int mark)
569 {
570     space *tadj[4], *eadj[4];
571     int i, didsth = 0, edge, same;
572
573     assert(tile->type == s_tile);
574     adjacencies(state, tile, eadj, tadj);
575     for (i = 0; i < 4; i++) {
576         if (!eadj[i]) continue;
577
578         edge = (eadj[i]->flags & F_EDGE_SET) ? 1 : 0;
579         if (tadj[i]) {
580             if (!(tile->flags & F_TILE_ASSOC))
581                 same = (tadj[i]->flags & F_TILE_ASSOC) ? 0 : 1;
582             else
583                 same = ((tadj[i]->flags & F_TILE_ASSOC) &&
584                     tile->dotx == tadj[i]->dotx &&
585                     tile->doty == tadj[i]->doty) ? 1 : 0;
586         } else
587             same = 0;
588
589         if (!edge && !same) {
590             if (mark) eadj[i]->flags |= F_EDGE_SET;
591             didsth = 1;
592         } else if (edge && same) {
593             if (mark) eadj[i]->flags &= ~F_EDGE_SET;
594             didsth = 1;
595         }
596     }
597     return didsth;
598 }
599
600 static void tiles_from_edge(game_state *state, space *sp, space **ts)
601 {
602     int xs[2], ys[2];
603
604     if (IS_VERTICAL_EDGE(sp->x)) {
605         xs[0] = sp->x-1; ys[0] = sp->y;
606         xs[1] = sp->x+1; ys[1] = sp->y;
607     } else {
608         xs[0] = sp->x; ys[0] = sp->y-1;
609         xs[1] = sp->x; ys[1] = sp->y+1;
610     }
611     ts[0] = INGRID(state, xs[0], ys[0]) ? &SPACE(state, xs[0], ys[0]) : NULL;
612     ts[1] = INGRID(state, xs[1], ys[1]) ? &SPACE(state, xs[1], ys[1]) : NULL;
613 }
614
615 /* Returns a move string for use by 'solve', including the initial
616  * 'S' if issolve is true. */
617 static char *diff_game(const game_state *src, const game_state *dest,
618                        int issolve)
619 {
620     int movelen = 0, movesize = 256, x, y, len;
621     char *move = snewn(movesize, char), buf[80], *sep = "";
622     char achar = issolve ? 'a' : 'A';
623     space *sps, *spd;
624
625     assert(src->sx == dest->sx && src->sy == dest->sy);
626
627     if (issolve) {
628         move[movelen++] = 'S';
629         sep = ";";
630     }
631     move[movelen] = '\0';
632     for (x = 0; x < src->sx; x++) {
633         for (y = 0; y < src->sy; y++) {
634             sps = &SPACE(src, x, y);
635             spd = &SPACE(dest, x, y);
636
637             assert(sps->type == spd->type);
638
639             len = 0;
640             if (sps->type == s_tile) {
641                 if ((sps->flags & F_TILE_ASSOC) &&
642                     (spd->flags & F_TILE_ASSOC)) {
643                     if (sps->dotx != spd->dotx ||
644                         sps->doty != spd->doty)
645                     /* Both associated; change association, if different */
646                         len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
647                                       (int)achar, x, y, spd->dotx, spd->doty);
648                 } else if (sps->flags & F_TILE_ASSOC)
649                     /* Only src associated; remove. */
650                     len = sprintf(buf, "%sU%d,%d", sep, x, y);
651                 else if (spd->flags & F_TILE_ASSOC)
652                     /* Only dest associated; add. */
653                     len = sprintf(buf, "%s%c%d,%d,%d,%d", sep,
654                                   (int)achar, x, y, spd->dotx, spd->doty);
655             } else if (sps->type == s_edge) {
656                 if ((sps->flags & F_EDGE_SET) != (spd->flags & F_EDGE_SET))
657                     /* edge flags are different; flip them. */
658                     len = sprintf(buf, "%sE%d,%d", sep, x, y);
659             }
660             if (len) {
661                 if (movelen + len >= movesize) {
662                     movesize = movelen + len + 256;
663                     move = sresize(move, movesize, char);
664                 }
665                 strcpy(move + movelen, buf);
666                 movelen += len;
667                 sep = ";";
668             }
669         }
670     }
671     debug(("diff_game src then dest:\n"));
672     dbg_state(src);
673     dbg_state(dest);
674     debug(("diff string %s\n", move));
675     return move;
676 }
677
678 /* Returns 1 if a dot here would not be too close to any other dots
679  * (and would avoid other game furniture). */
680 static int dot_is_possible(game_state *state, space *sp, int allow_assoc)
681 {
682     int bx = 0, by = 0, dx, dy;
683     space *adj;
684 #ifdef STANDALONE_PICTURE_GENERATOR
685     int col = -1;
686 #endif
687
688     switch (sp->type) {
689     case s_tile:
690         bx = by = 1; break;
691     case s_edge:
692         if (IS_VERTICAL_EDGE(sp->x)) {
693             bx = 2; by = 1;
694         } else {
695             bx = 1; by = 2;
696         }
697         break;
698     case s_vertex:
699         bx = by = 2; break;
700     }
701
702     for (dx = -bx; dx <= bx; dx++) {
703         for (dy = -by; dy <= by; dy++) {
704             if (!INGRID(state, sp->x+dx, sp->y+dy)) continue;
705
706             adj = &SPACE(state, sp->x+dx, sp->y+dy);
707
708 #ifdef STANDALONE_PICTURE_GENERATOR
709             /*
710              * Check that all the squares we're looking at have the
711              * same colour.
712              */
713             if (picture) {
714                 if (adj->type == s_tile) {
715                     int c = picture[(adj->y / 2) * state->w + (adj->x / 2)];
716                     if (col < 0)
717                         col = c;
718                     if (c != col)
719                         return 0;          /* colour mismatch */
720                 }
721             }
722 #endif
723
724             if (!allow_assoc && (adj->flags & F_TILE_ASSOC))
725                 return 0;
726
727             if (dx != 0 || dy != 0) {
728                 /* Other than our own square, no dots nearby. */
729                 if (adj->flags & (F_DOT))
730                     return 0;
731             }
732
733             /* We don't want edges within our rectangle
734              * (but don't care about edges on the edge) */
735             if (abs(dx) < bx && abs(dy) < by &&
736                 adj->flags & F_EDGE_SET)
737                 return 0;
738         }
739     }
740     return 1;
741 }
742
743 /* ----------------------------------------------------------
744  * Game generation, structure creation, and descriptions.
745  */
746
747 static game_state *blank_game(int w, int h)
748 {
749     game_state *state = snew(game_state);
750     int x, y;
751
752     state->w = w;
753     state->h = h;
754
755     state->sx = (w*2)+1;
756     state->sy = (h*2)+1;
757     state->grid = snewn(state->sx * state->sy, space);
758     state->completed = state->used_solve = 0;
759
760     for (x = 0; x < state->sx; x++) {
761         for (y = 0; y < state->sy; y++) {
762             space *sp = &SPACE(state, x, y);
763             memset(sp, 0, sizeof(space));
764             sp->x = x;
765             sp->y = y;
766             if ((x % 2) == 0 && (y % 2) == 0)
767                 sp->type = s_vertex;
768             else if ((x % 2) == 0 || (y % 2) == 0) {
769                 sp->type = s_edge;
770                 if (x == 0 || y == 0 || x == state->sx-1 || y == state->sy-1)
771                     sp->flags |= F_EDGE_SET;
772             } else
773                 sp->type = s_tile;
774         }
775     }
776
777     state->ndots = 0;
778     state->dots = NULL;
779
780     state->me = NULL; /* filled in by new_game. */
781     state->cdiff = -1;
782
783     return state;
784 }
785
786 static void game_update_dots(game_state *state)
787 {
788     int i, n, sz = state->sx * state->sy;
789
790     if (state->dots) sfree(state->dots);
791     state->ndots = 0;
792
793     for (i = 0; i < sz; i++) {
794         if (state->grid[i].flags & F_DOT) state->ndots++;
795     }
796     state->dots = snewn(state->ndots, space *);
797     n = 0;
798     for (i = 0; i < sz; i++) {
799         if (state->grid[i].flags & F_DOT)
800             state->dots[n++] = &state->grid[i];
801     }
802 }
803
804 static void clear_game(game_state *state, int cleardots)
805 {
806     int x, y;
807
808     /* don't erase edge flags around outline! */
809     for (x = 1; x < state->sx-1; x++) {
810         for (y = 1; y < state->sy-1; y++) {
811             if (cleardots)
812                 SPACE(state, x, y).flags = 0;
813             else
814                 SPACE(state, x, y).flags &= (F_DOT|F_DOT_BLACK);
815         }
816     }
817     if (cleardots) game_update_dots(state);
818 }
819
820 static game_state *dup_game(const game_state *state)
821 {
822     game_state *ret = blank_game(state->w, state->h);
823
824     ret->completed = state->completed;
825     ret->used_solve = state->used_solve;
826
827     memcpy(ret->grid, state->grid,
828            ret->sx*ret->sy*sizeof(space));
829
830     game_update_dots(ret);
831
832     ret->me = state->me;
833     ret->cdiff = state->cdiff;
834
835     return ret;
836 }
837
838 static void free_game(game_state *state)
839 {
840     if (state->dots) sfree(state->dots);
841     sfree(state->grid);
842     sfree(state);
843 }
844
845 /* Game description is a sequence of letters representing the number
846  * of spaces (a = 0, y = 24) before the next dot; a-y for a white dot,
847  * and A-Y for a black dot. 'z' is 25 spaces (and no dot).
848  *
849  * I know it's a bitch to generate by hand, so we provide
850  * an edit mode.
851  */
852
853 static char *encode_game(game_state *state)
854 {
855     char *desc, *p;
856     int run, x, y, area;
857     unsigned int f;
858
859     area = (state->sx-2) * (state->sy-2);
860
861     desc = snewn(area, char);
862     p = desc;
863     run = 0;
864     for (y = 1; y < state->sy-1; y++) {
865         for (x = 1; x < state->sx-1; x++) {
866             f = SPACE(state, x, y).flags;
867
868             /* a/A is 0 spaces between, b/B is 1 space, ...
869              * y/Y is 24 spaces, za/zA is 25 spaces, ...
870              * It's easier to count from 0 because we then
871              * don't have to special-case the top left-hand corner
872              * (which could be a dot with 0 spaces before it). */
873             if (!(f & F_DOT))
874                 run++;
875             else {
876                 while (run > 24) {
877                     *p++ = 'z';
878                     run -= 25;
879                 }
880                 *p++ = ((f & F_DOT_BLACK) ? 'A' : 'a') + run;
881                 run = 0;
882             }
883         }
884     }
885     assert(p - desc < area);
886     *p++ = '\0';
887     desc = sresize(desc, p - desc, char);
888
889     return desc;
890 }
891
892 struct movedot {
893     int op;
894     space *olddot, *newdot;
895 };
896
897 enum { MD_CHECK, MD_MOVE };
898
899 static int movedot_cb(game_state *state, space *tile, void *vctx)
900 {
901    struct movedot *md = (struct movedot *)vctx;
902    space *newopp = NULL;
903
904    assert(tile->type == s_tile);
905    assert(md->olddot && md->newdot);
906
907    if (!(tile->flags & F_TILE_ASSOC)) return 0;
908    if (tile->dotx != md->olddot->x || tile->doty != md->olddot->y)
909        return 0;
910
911    newopp = space_opposite_dot(state, tile, md->newdot);
912
913    switch (md->op) {
914    case MD_CHECK:
915        /* If the tile is associated with the old dot, check its
916         * opposite wrt the _new_ dot is empty or same assoc. */
917        if (!newopp) return -1; /* no new opposite */
918        if (newopp->flags & F_TILE_ASSOC) {
919            if (newopp->dotx != md->olddot->x ||
920                newopp->doty != md->olddot->y)
921                return -1; /* associated, but wrong dot. */
922        }
923 #ifdef STANDALONE_PICTURE_GENERATOR
924        if (picture) {
925            /*
926             * Reject if either tile and the dot don't match in colour.
927             */
928            if (!(picture[(tile->y/2) * state->w + (tile->x/2)]) ^
929                !(md->newdot->flags & F_DOT_BLACK))
930                return -1;
931            if (!(picture[(newopp->y/2) * state->w + (newopp->x/2)]) ^
932                !(md->newdot->flags & F_DOT_BLACK))
933                return -1;
934        }
935 #endif
936        break;
937
938    case MD_MOVE:
939        /* Move dot associations: anything that was associated
940         * with the old dot, and its opposite wrt the new dot,
941         * become associated with the new dot. */
942        assert(newopp);
943        debug(("Associating %d,%d and %d,%d with new dot %d,%d.\n",
944               tile->x, tile->y, newopp->x, newopp->y,
945               md->newdot->x, md->newdot->y));
946        add_assoc(state, tile, md->newdot);
947        add_assoc(state, newopp, md->newdot);
948        return 1; /* we did something! */
949    }
950    return 0;
951 }
952
953 /* For the given dot, first see if we could expand it into all the given
954  * extra spaces (by checking for empty spaces on the far side), and then
955  * see if we can move the dot to shift the CoG to include the new spaces.
956  */
957 static int dot_expand_or_move(game_state *state, space *dot,
958                               space **toadd, int nadd)
959 {
960     space *tileopp;
961     int i, ret, nnew, cx, cy;
962     struct movedot md;
963
964     debug(("dot_expand_or_move: %d tiles for dot %d,%d\n",
965            nadd, dot->x, dot->y));
966     for (i = 0; i < nadd; i++)
967         debug(("dot_expand_or_move:   dot %d,%d\n",
968                toadd[i]->x, toadd[i]->y));
969     assert(dot->flags & F_DOT);
970
971 #ifdef STANDALONE_PICTURE_GENERATOR
972     if (picture) {
973         /*
974          * Reject the expansion totally if any of the new tiles are
975          * the wrong colour.
976          */
977         for (i = 0; i < nadd; i++) {
978             if (!(picture[(toadd[i]->y/2) * state->w + (toadd[i]->x/2)]) ^
979                 !(dot->flags & F_DOT_BLACK))
980                 return 0;
981         }
982     }
983 #endif
984
985     /* First off, could we just expand the current dot's tile to cover
986      * the space(s) passed in and their opposites? */
987     for (i = 0; i < nadd; i++) {
988         tileopp = space_opposite_dot(state, toadd[i], dot);
989         if (!tileopp) goto noexpand;
990         if (tileopp->flags & F_TILE_ASSOC) goto noexpand;
991 #ifdef STANDALONE_PICTURE_GENERATOR
992         if (picture) {
993             /*
994              * The opposite tiles have to be the right colour as well.
995              */
996             if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
997                 !(dot->flags & F_DOT_BLACK))
998                 goto noexpand;
999         }
1000 #endif
1001     }
1002     /* OK, all spaces have valid empty opposites: associate spaces and
1003      * opposites with our dot. */
1004     for (i = 0; i < nadd; i++) {
1005         tileopp = space_opposite_dot(state, toadd[i], dot);
1006         add_assoc(state, toadd[i], dot);
1007         add_assoc(state, tileopp, dot);
1008         debug(("Added associations %d,%d and %d,%d --> %d,%d\n",
1009                toadd[i]->x, toadd[i]->y,
1010                tileopp->x, tileopp->y,
1011                dot->x, dot->y));
1012         dbg_state(state);
1013     }
1014     return 1;
1015
1016 noexpand:
1017     /* Otherwise, try to move dot so as to encompass given spaces: */
1018     /* first, calculate the 'centre of gravity' of the new dot. */
1019     nnew = dot->nassoc + nadd; /* number of tiles assoc. with new dot. */
1020     cx = dot->x * dot->nassoc;
1021     cy = dot->y * dot->nassoc;
1022     for (i = 0; i < nadd; i++) {
1023         cx += toadd[i]->x;
1024         cy += toadd[i]->y;
1025     }
1026     /* If the CoG isn't a whole number, it's not possible. */
1027     if ((cx % nnew) != 0 || (cy % nnew) != 0) {
1028         debug(("Unable to move dot %d,%d, CoG not whole number.\n",
1029                dot->x, dot->y));
1030         return 0;
1031     }
1032     cx /= nnew; cy /= nnew;
1033
1034     /* Check whether all spaces in the old tile would have a good
1035      * opposite wrt the new dot. */
1036     md.olddot = dot;
1037     md.newdot = &SPACE(state, cx, cy);
1038     md.op = MD_CHECK;
1039     ret = foreach_tile(state, movedot_cb, IMPOSSIBLE_QUITS, &md);
1040     if (ret == -1) {
1041         debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1042                dot->x, dot->y));
1043         return 0;
1044     }
1045     /* Also check whether all spaces we're adding would have a good
1046      * opposite wrt the new dot. */
1047     for (i = 0; i < nadd; i++) {
1048         tileopp = space_opposite_dot(state, toadd[i], md.newdot);
1049         if (tileopp && (tileopp->flags & F_TILE_ASSOC) &&
1050             (tileopp->dotx != dot->x || tileopp->doty != dot->y)) {
1051             tileopp = NULL;
1052         }
1053         if (!tileopp) {
1054             debug(("Unable to move dot %d,%d, new dot not symmetrical.\n",
1055                dot->x, dot->y));
1056             return 0;
1057         }
1058 #ifdef STANDALONE_PICTURE_GENERATOR
1059         if (picture) {
1060             if (!(picture[(tileopp->y/2) * state->w + (tileopp->x/2)]) ^
1061                 !(dot->flags & F_DOT_BLACK))
1062                 return 0;
1063         }
1064 #endif
1065     }
1066
1067     /* If we've got here, we're ok. First, associate all of 'toadd'
1068      * with the _old_ dot (so they'll get fixed up, with their opposites,
1069      * in the next step). */
1070     for (i = 0; i < nadd; i++) {
1071         debug(("Associating to-add %d,%d with old dot %d,%d.\n",
1072                toadd[i]->x, toadd[i]->y, dot->x, dot->y));
1073         add_assoc(state, toadd[i], dot);
1074     }
1075
1076     /* Finally, move the dot and fix up all the old associations. */
1077     debug(("Moving dot at %d,%d to %d,%d\n",
1078            dot->x, dot->y, md.newdot->x, md.newdot->y));
1079     {
1080 #ifdef STANDALONE_PICTURE_GENERATOR
1081         int f = dot->flags & F_DOT_BLACK;
1082 #endif
1083         remove_dot(dot);
1084         add_dot(md.newdot);
1085 #ifdef STANDALONE_PICTURE_GENERATOR
1086         md.newdot->flags |= f;
1087 #endif
1088     }
1089
1090     md.op = MD_MOVE;
1091     ret = foreach_tile(state, movedot_cb, 0, &md);
1092     assert(ret == 1);
1093     dbg_state(state);
1094
1095     return 1;
1096 }
1097
1098 /* Hard-code to a max. of 2x2 squares, for speed (less malloc) */
1099 #define MAX_TOADD 4
1100 #define MAX_OUTSIDE 8
1101
1102 #define MAX_TILE_PERC 20
1103
1104 static int generate_try_block(game_state *state, random_state *rs,
1105                               int x1, int y1, int x2, int y2)
1106 {
1107     int x, y, nadd = 0, nout = 0, i, maxsz;
1108     space *sp, *toadd[MAX_TOADD], *outside[MAX_OUTSIDE], *dot;
1109
1110     if (!INGRID(state, x1, y1) || !INGRID(state, x2, y2)) return 0;
1111
1112     /* We limit the maximum size of tiles to be ~2*sqrt(area); so,
1113      * a 5x5 grid shouldn't have anything >10 tiles, a 20x20 grid
1114      * nothing >40 tiles. */
1115     maxsz = (int)sqrt((double)(state->w * state->h)) * 2;
1116     debug(("generate_try_block, maxsz %d\n", maxsz));
1117
1118     /* Make a static list of the spaces; if any space is already
1119      * associated then quit immediately. */
1120     for (x = x1; x <= x2; x += 2) {
1121         for (y = y1; y <= y2; y += 2) {
1122             assert(nadd < MAX_TOADD);
1123             sp = &SPACE(state, x, y);
1124             assert(sp->type == s_tile);
1125             if (sp->flags & F_TILE_ASSOC) return 0;
1126             toadd[nadd++] = sp;
1127         }
1128     }
1129
1130     /* Make a list of the spaces outside of our block, and shuffle it. */
1131 #define OUTSIDE(x, y) do {                              \
1132     if (INGRID(state, (x), (y))) {                      \
1133         assert(nout < MAX_OUTSIDE);                     \
1134         outside[nout++] = &SPACE(state, (x), (y));      \
1135     }                                                   \
1136 } while(0)
1137     for (x = x1; x <= x2; x += 2) {
1138         OUTSIDE(x, y1-2);
1139         OUTSIDE(x, y2+2);
1140     }
1141     for (y = y1; y <= y2; y += 2) {
1142         OUTSIDE(x1-2, y);
1143         OUTSIDE(x2+2, y);
1144     }
1145     shuffle(outside, nout, sizeof(space *), rs);
1146
1147     for (i = 0; i < nout; i++) {
1148         if (!(outside[i]->flags & F_TILE_ASSOC)) continue;
1149         dot = &SPACE(state, outside[i]->dotx, outside[i]->doty);
1150         if (dot->nassoc >= maxsz) {
1151             debug(("Not adding to dot %d,%d, large enough (%d) already.\n",
1152                    dot->x, dot->y, dot->nassoc));
1153             continue;
1154         }
1155         if (dot_expand_or_move(state, dot, toadd, nadd)) return 1;
1156     }
1157     return 0;
1158 }
1159
1160 #ifdef STANDALONE_SOLVER
1161 int maxtries;
1162 #define MAXTRIES maxtries
1163 #else
1164 #define MAXTRIES 50
1165 #endif
1166
1167 static int solver_obvious_dot(game_state *state,space *dot);
1168
1169 #define GP_DOTS   1
1170
1171 static void generate_pass(game_state *state, random_state *rs, int *scratch,
1172                          int perc, unsigned int flags)
1173 {
1174     int sz = state->sx*state->sy, nspc, i, ret;
1175
1176     shuffle(scratch, sz, sizeof(int), rs);
1177
1178     /* This bug took me a, er, little while to track down. On PalmOS,
1179      * which has 16-bit signed ints, puzzles over about 9x9 started
1180      * failing to generate because the nspc calculation would start
1181      * to overflow, causing the dots not to be filled in properly. */
1182     nspc = (int)(((long)perc * (long)sz) / 100L);
1183     debug(("generate_pass: %d%% (%d of %dx%d) squares, flags 0x%x\n",
1184            perc, nspc, state->sx, state->sy, flags));
1185
1186     for (i = 0; i < nspc; i++) {
1187         space *sp = &state->grid[scratch[i]];
1188         int x1 = sp->x, y1 = sp->y, x2 = sp->x, y2 = sp->y;
1189
1190         if (sp->type == s_edge) {
1191             if (IS_VERTICAL_EDGE(sp->x)) {
1192                 x1--; x2++;
1193             } else {
1194                 y1--; y2++;
1195             }
1196         }
1197         if (sp->type != s_vertex) {
1198             /* heuristic; expanding from vertices tends to generate lots of
1199              * too-big regions of tiles. */
1200             if (generate_try_block(state, rs, x1, y1, x2, y2))
1201                 continue; /* we expanded successfully. */
1202         }
1203
1204         if (!(flags & GP_DOTS)) continue;
1205
1206         if ((sp->type == s_edge) && (i % 2)) {
1207             debug(("Omitting edge %d,%d as half-of.\n", sp->x, sp->y));
1208             continue;
1209         }
1210
1211         /* If we've got here we might want to put a dot down. Check
1212          * if we can, and add one if so. */
1213         if (dot_is_possible(state, sp, 0)) {
1214             add_dot(sp);
1215 #ifdef STANDALONE_PICTURE_GENERATOR
1216             if (picture) {
1217                 if (picture[(sp->y/2) * state->w + (sp->x/2)])
1218                     sp->flags |= F_DOT_BLACK;
1219             }
1220 #endif
1221             ret = solver_obvious_dot(state, sp);
1222             assert(ret != -1);
1223             debug(("Added dot (and obvious associations) at %d,%d\n",
1224                    sp->x, sp->y));
1225             dbg_state(state);
1226         }
1227     }
1228     dbg_state(state);
1229 }
1230
1231 static int check_complete(const game_state *state, int *dsf, int *colours);
1232 static int solver_state(game_state *state, int maxdiff);
1233
1234 static char *new_game_desc(const game_params *params, random_state *rs,
1235                            char **aux, int interactive)
1236 {
1237     game_state *state = blank_game(params->w, params->h), *copy;
1238     char *desc;
1239     int *scratch, sz = state->sx*state->sy, i;
1240     int diff, ntries = 0, cc;
1241
1242     /* Random list of squares to try and process, one-by-one. */
1243     scratch = snewn(sz, int);
1244     for (i = 0; i < sz; i++) scratch[i] = i;
1245
1246 generate:
1247     clear_game(state, 1);
1248     ntries++;
1249
1250     /* generate_pass(state, rs, scratch, 10, GP_DOTS); */
1251     /* generate_pass(state, rs, scratch, 100, 0); */
1252     generate_pass(state, rs, scratch, 100, GP_DOTS);
1253
1254     game_update_dots(state);
1255
1256 #ifdef DEBUGGING
1257     {
1258         char *tmp = encode_game(state);
1259         debug(("new_game_desc state %dx%d:%s\n", params->w, params->h, tmp));
1260         sfree(tmp);
1261     }
1262 #endif
1263
1264     for (i = 0; i < state->sx*state->sy; i++)
1265         if (state->grid[i].type == s_tile)
1266             outline_tile_fordot(state, &state->grid[i], TRUE);
1267     cc = check_complete(state, NULL, NULL);
1268     assert(cc);
1269
1270     copy = dup_game(state);
1271     clear_game(copy, 0);
1272     dbg_state(copy);
1273     diff = solver_state(copy, params->diff);
1274     free_game(copy);
1275
1276     assert(diff != DIFF_IMPOSSIBLE);
1277     if (diff != params->diff) {
1278         /*
1279          * We'll grudgingly accept a too-easy puzzle, but we must
1280          * _not_ permit a too-hard one (one which the solver
1281          * couldn't handle at all).
1282          */
1283         if (diff > params->diff ||
1284             ntries < MAXTRIES) goto generate;
1285     }
1286
1287 #ifdef STANDALONE_PICTURE_GENERATOR
1288     /*
1289      * Postprocessing pass to prevent excessive numbers of adjacent
1290      * singletons. Iterate over all edges in random shuffled order;
1291      * for each edge that separates two regions, investigate
1292      * whether removing that edge and merging the regions would
1293      * still yield a valid and soluble puzzle. (The two regions
1294      * must also be the same colour, of course.) If so, do it.
1295      * 
1296      * This postprocessing pass is slow (due to repeated solver
1297      * invocations), and seems to be unnecessary during normal
1298      * unconstrained game generation. However, when generating a
1299      * game under colour constraints, excessive singletons seem to
1300      * turn up more often, so it's worth doing this.
1301      */
1302     {
1303         int *posns, nposns;
1304         int i, j, newdiff;
1305         game_state *copy2;
1306
1307         nposns = params->w * (params->h+1) + params->h * (params->w+1);
1308         posns = snewn(nposns, int);
1309         for (i = j = 0; i < state->sx*state->sy; i++)
1310             if (state->grid[i].type == s_edge)
1311                 posns[j++] = i;
1312         assert(j == nposns);
1313
1314         shuffle(posns, nposns, sizeof(*posns), rs);
1315
1316         for (i = 0; i < nposns; i++) {
1317             int x, y, x0, y0, x1, y1, cx, cy, cn, cx0, cy0, cx1, cy1, tx, ty;
1318             space *s0, *s1, *ts, *d0, *d1, *dn;
1319             int ok;
1320
1321             /* Coordinates of edge space */
1322             x = posns[i] % state->sx;
1323             y = posns[i] / state->sx;
1324
1325             /* Coordinates of square spaces on either side of edge */
1326             x0 = ((x+1) & ~1) - 1;     /* round down to next odd number */
1327             y0 = ((y+1) & ~1) - 1;
1328             x1 = 2*x-x0;               /* and reflect about x to get x1 */
1329             y1 = 2*y-y0;
1330
1331             if (!INGRID(state, x0, y0) || !INGRID(state, x1, y1))
1332                 continue;              /* outermost edge of grid */
1333             s0 = &SPACE(state, x0, y0);
1334             s1 = &SPACE(state, x1, y1);
1335             assert(s0->type == s_tile && s1->type == s_tile);
1336
1337             if (s0->dotx == s1->dotx && s0->doty == s1->doty)
1338                 continue;              /* tiles _already_ owned by same dot */
1339
1340             d0 = &SPACE(state, s0->dotx, s0->doty);
1341             d1 = &SPACE(state, s1->dotx, s1->doty);
1342
1343             if ((d0->flags ^ d1->flags) & F_DOT_BLACK)
1344                 continue;              /* different colours: cannot merge */
1345
1346             /*
1347              * Work out where the centre of gravity of the new
1348              * region would be.
1349              */
1350             cx = d0->nassoc * d0->x + d1->nassoc * d1->x;
1351             cy = d0->nassoc * d0->y + d1->nassoc * d1->y;
1352             cn = d0->nassoc + d1->nassoc;
1353             if (cx % cn || cy % cn)
1354                 continue;              /* CoG not at integer coordinates */
1355             cx /= cn;
1356             cy /= cn;
1357             assert(INUI(state, cx, cy));
1358
1359             /*
1360              * Ensure that the CoG would actually be _in_ the new
1361              * region, by verifying that all its surrounding tiles
1362              * belong to one or other of our two dots.
1363              */
1364             cx0 = ((cx+1) & ~1) - 1;   /* round down to next odd number */
1365             cy0 = ((cy+1) & ~1) - 1;
1366             cx1 = 2*cx-cx0;            /* and reflect about cx to get cx1 */
1367             cy1 = 2*cy-cy0;
1368             ok = TRUE;
1369             for (ty = cy0; ty <= cy1; ty += 2)
1370                 for (tx = cx0; tx <= cx1; tx += 2) {
1371                     ts = &SPACE(state, tx, ty);
1372                     assert(ts->type == s_tile);
1373                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1374                         (ts->dotx != d1->x || ts->doty != d1->y))
1375                         ok = FALSE;
1376                 }
1377             if (!ok)
1378                 continue;
1379
1380             /*
1381              * Verify that for every tile in either source region,
1382              * that tile's image in the new CoG is also in one of
1383              * the two source regions.
1384              */
1385             for (ty = 1; ty < state->sy; ty += 2) {
1386                 for (tx = 1; tx < state->sx; tx += 2) {
1387                     int tx1, ty1;
1388
1389                     ts = &SPACE(state, tx, ty);
1390                     assert(ts->type == s_tile);
1391                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1392                         (ts->dotx != d1->x || ts->doty != d1->y))
1393                         continue;      /* not part of these tiles anyway */
1394                     tx1 = 2*cx-tx;
1395                     ty1 = 2*cy-ty;
1396                     if (!INGRID(state, tx1, ty1)) {
1397                         ok = FALSE;
1398                         break;
1399                     }
1400                     ts = &SPACE(state, cx+cx-tx, cy+cy-ty);
1401                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1402                         (ts->dotx != d1->x || ts->doty != d1->y)) {
1403                         ok = FALSE;
1404                         break;
1405                     }
1406                 }
1407                 if (!ok)
1408                     break;
1409             }
1410             if (!ok)
1411                 continue;
1412
1413             /*
1414              * Now we're clear to attempt the merge. We take a copy
1415              * of the game state first, so we can revert it easily
1416              * if the resulting puzzle turns out to have become
1417              * insoluble.
1418              */
1419             copy2 = dup_game(state);
1420
1421             remove_dot(d0);
1422             remove_dot(d1);
1423             dn = &SPACE(state, cx, cy);
1424             add_dot(dn);
1425             dn->flags |= (d0->flags & F_DOT_BLACK);
1426             for (ty = 1; ty < state->sy; ty += 2) {
1427                 for (tx = 1; tx < state->sx; tx += 2) {
1428                     ts = &SPACE(state, tx, ty);
1429                     assert(ts->type == s_tile);
1430                     if ((ts->dotx != d0->x || ts->doty != d0->y) &&
1431                         (ts->dotx != d1->x || ts->doty != d1->y))
1432                         continue;      /* not part of these tiles anyway */
1433                     add_assoc(state, ts, dn);
1434                 }
1435             }
1436
1437             copy = dup_game(state);
1438             clear_game(copy, 0);
1439             dbg_state(copy);
1440             newdiff = solver_state(copy, params->diff);
1441             free_game(copy);
1442             if (diff == newdiff) {
1443                 /* Still just as soluble. Let the merge stand. */
1444                 free_game(copy2);
1445             } else {
1446                 /* Became insoluble. Revert. */
1447                 free_game(state);
1448                 state = copy2;
1449             }
1450         }
1451         sfree(posns);
1452     }
1453 #endif
1454
1455     desc = encode_game(state);
1456 #ifndef STANDALONE_SOLVER
1457     debug(("new_game_desc generated: \n"));
1458     dbg_state(state);
1459 #endif
1460
1461     free_game(state);
1462     sfree(scratch);
1463
1464     return desc;
1465 }
1466
1467 static int solver_obvious(game_state *state);
1468
1469 static int dots_too_close(game_state *state)
1470 {
1471     /* Quick-and-dirty check, using half the solver:
1472      * solver_obvious will only fail if the dots are
1473      * too close together, so dot-proximity associations
1474      * overlap. */
1475     game_state *tmp = dup_game(state);
1476     int ret = solver_obvious(tmp);
1477     free_game(tmp);
1478     return (ret == -1) ? 1 : 0;
1479 }
1480
1481 static game_state *load_game(const game_params *params, const char *desc,
1482                              char **why_r)
1483 {
1484     game_state *state = blank_game(params->w, params->h);
1485     char *why = NULL;
1486     int i, x, y, n;
1487     unsigned int df;
1488
1489     i = 0;
1490     while (*desc) {
1491         n = *desc++;
1492         if (n == 'z') {
1493             i += 25;
1494             continue;
1495         }
1496         if (n >= 'a' && n <= 'y') {
1497             i += n - 'a';
1498             df = 0;
1499         } else if (n >= 'A' && n <= 'Y') {
1500             i += n - 'A';
1501             df = F_DOT_BLACK;
1502         } else {
1503             why = "Invalid characters in game description"; goto fail;
1504         }
1505         /* if we got here we incremented i and have a dot to add. */
1506         y = (i / (state->sx-2)) + 1;
1507         x = (i % (state->sx-2)) + 1;
1508         if (!INUI(state, x, y)) {
1509             why = "Too much data to fit in grid"; goto fail;
1510         }
1511         add_dot(&SPACE(state, x, y));
1512         SPACE(state, x, y).flags |= df;
1513         i++;
1514     }
1515     game_update_dots(state);
1516
1517     if (dots_too_close(state)) {
1518         why = "Dots too close together"; goto fail;
1519     }
1520
1521     return state;
1522
1523 fail:
1524     free_game(state);
1525     if (why_r) *why_r = why;
1526     return NULL;
1527 }
1528
1529 static char *validate_desc(const game_params *params, const char *desc)
1530 {
1531     char *why = NULL;
1532     game_state *dummy = load_game(params, desc, &why);
1533     if (dummy) {
1534         free_game(dummy);
1535         assert(!why);
1536     } else
1537         assert(why);
1538     return why;
1539 }
1540
1541 static game_state *new_game(midend *me, const game_params *params,
1542                             const char *desc)
1543 {
1544     game_state *state = load_game(params, desc, NULL);
1545     if (!state) {
1546         assert("Unable to load ?validated game.");
1547         return NULL;
1548     }
1549 #ifdef EDITOR
1550     state->me = me;
1551 #endif
1552     return state;
1553 }
1554
1555 /* ----------------------------------------------------------
1556  * Solver and all its little wizards.
1557  */
1558
1559 int solver_recurse_depth;
1560
1561 typedef struct solver_ctx {
1562     game_state *state;
1563     int sz;             /* state->sx * state->sy */
1564     space **scratch;    /* size sz */
1565
1566 } solver_ctx;
1567
1568 static solver_ctx *new_solver(game_state *state)
1569 {
1570     solver_ctx *sctx = snew(solver_ctx);
1571     sctx->state = state;
1572     sctx->sz = state->sx*state->sy;
1573     sctx->scratch = snewn(sctx->sz, space *);
1574     return sctx;
1575 }
1576
1577 static void free_solver(solver_ctx *sctx)
1578 {
1579     sfree(sctx->scratch);
1580     sfree(sctx);
1581 }
1582
1583     /* Solver ideas so far:
1584      *
1585      * For any empty space, work out how many dots it could associate
1586      * with:
1587        * it needs line-of-sight
1588        * it needs an empty space on the far side
1589        * any adjacent lines need corresponding line possibilities.
1590      */
1591
1592 /* The solver_ctx should keep a list of dot positions, for quicker looping.
1593  *
1594  * Solver techniques, in order of difficulty:
1595    * obvious adjacency to dots
1596    * transferring tiles to opposite side
1597    * transferring lines to opposite side
1598    * one possible dot for a given tile based on opposite availability
1599    * tile with 3 definite edges next to an associated tile must associate
1600       with same dot.
1601    *
1602    * one possible dot for a given tile based on line-of-sight
1603  */
1604
1605 static int solver_add_assoc(game_state *state, space *tile, int dx, int dy,
1606                             const char *why)
1607 {
1608     space *dot, *tile_opp;
1609
1610     dot = &SPACE(state, dx, dy);
1611     tile_opp = space_opposite_dot(state, tile, dot);
1612
1613     assert(tile->type == s_tile);
1614     if (tile->flags & F_TILE_ASSOC) {
1615         if ((tile->dotx != dx) || (tile->doty != dy)) {
1616             solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1617                     "already --> %d,%d.\n",
1618                     solver_recurse_depth*4, "",
1619                     tile->x, tile->y, dx, dy, why,
1620                     tile->dotx, tile->doty));
1621             return -1;
1622         }
1623         return 0; /* no-op */
1624     }
1625     if (!tile_opp) {
1626         solvep(("%*s%d,%d --> %d,%d impossible, no opposite tile.\n",
1627                 solver_recurse_depth*4, "", tile->x, tile->y, dx, dy));
1628         return -1;
1629     }
1630     if (tile_opp->flags & F_TILE_ASSOC &&
1631         (tile_opp->dotx != dx || tile_opp->doty != dy)) {
1632         solvep(("%*sSet %d,%d --> %d,%d (%s) impossible; "
1633                 "opposite already --> %d,%d.\n",
1634                 solver_recurse_depth*4, "",
1635                 tile->x, tile->y, dx, dy, why,
1636                 tile_opp->dotx, tile_opp->doty));
1637         return -1;
1638     }
1639
1640     add_assoc(state, tile, dot);
1641     add_assoc(state, tile_opp, dot);
1642     solvep(("%*sSetting %d,%d --> %d,%d (%s).\n",
1643             solver_recurse_depth*4, "",
1644             tile->x, tile->y,dx, dy, why));
1645     solvep(("%*sSetting %d,%d --> %d,%d (%s, opposite).\n",
1646             solver_recurse_depth*4, "",
1647             tile_opp->x, tile_opp->y, dx, dy, why));
1648     return 1;
1649 }
1650
1651 static int solver_obvious_dot(game_state *state, space *dot)
1652 {
1653     int dx, dy, ret, didsth = 0;
1654     space *tile;
1655
1656     debug(("%*ssolver_obvious_dot for %d,%d.\n",
1657            solver_recurse_depth*4, "", dot->x, dot->y));
1658
1659     assert(dot->flags & F_DOT);
1660     for (dx = -1; dx <= 1; dx++) {
1661         for (dy = -1; dy <= 1; dy++) {
1662             if (!INGRID(state, dot->x+dx, dot->y+dy)) continue;
1663
1664             tile = &SPACE(state, dot->x+dx, dot->y+dy);
1665             if (tile->type == s_tile) {
1666                 ret = solver_add_assoc(state, tile, dot->x, dot->y,
1667                                        "next to dot");
1668                 if (ret < 0) return -1;
1669                 if (ret > 0) didsth = 1;
1670             }
1671         }
1672     }
1673     return didsth;
1674 }
1675
1676 static int solver_obvious(game_state *state)
1677 {
1678     int i, didsth = 0, ret;
1679
1680     debug(("%*ssolver_obvious.\n", solver_recurse_depth*4, ""));
1681
1682     for (i = 0; i < state->ndots; i++) {
1683         ret = solver_obvious_dot(state, state->dots[i]);
1684         if (ret < 0) return -1;
1685         if (ret > 0) didsth = 1;
1686     }
1687     return didsth;
1688 }
1689
1690 static int solver_lines_opposite_cb(game_state *state, space *edge, void *ctx)
1691 {
1692     int didsth = 0, n, dx, dy;
1693     space *tiles[2], *tile_opp, *edge_opp;
1694
1695     assert(edge->type == s_edge);
1696
1697     tiles_from_edge(state, edge, tiles);
1698
1699     /* if tiles[0] && tiles[1] && they're both associated
1700      * and they're both associated with different dots,
1701      * ensure the line is set. */
1702     if (!(edge->flags & F_EDGE_SET) &&
1703         tiles[0] && tiles[1] &&
1704         (tiles[0]->flags & F_TILE_ASSOC) &&
1705         (tiles[1]->flags & F_TILE_ASSOC) &&
1706         (tiles[0]->dotx != tiles[1]->dotx ||
1707          tiles[0]->doty != tiles[1]->doty)) {
1708         /* No edge, but the two adjacent tiles are both
1709          * associated with different dots; add the edge. */
1710         solvep(("%*sSetting edge %d,%d - tiles different dots.\n",
1711                solver_recurse_depth*4, "", edge->x, edge->y));
1712         edge->flags |= F_EDGE_SET;
1713         didsth = 1;
1714     }
1715
1716     if (!(edge->flags & F_EDGE_SET)) return didsth;
1717     for (n = 0; n < 2; n++) {
1718         if (!tiles[n]) continue;
1719         assert(tiles[n]->type == s_tile);
1720         if (!(tiles[n]->flags & F_TILE_ASSOC)) continue;
1721
1722         tile_opp = tile_opposite(state, tiles[n]);
1723         if (!tile_opp) {
1724             solvep(("%*simpossible: edge %d,%d has assoc. tile %d,%d"
1725                    " with no opposite.\n",
1726                    solver_recurse_depth*4, "",
1727                    edge->x, edge->y, tiles[n]->x, tiles[n]->y));
1728             /* edge of tile has no opposite edge (off grid?);
1729              * this is impossible. */
1730             return -1;
1731         }
1732
1733         dx = tiles[n]->x - edge->x;
1734         dy = tiles[n]->y - edge->y;
1735         assert(INGRID(state, tile_opp->x+dx, tile_opp->y+dy));
1736         edge_opp = &SPACE(state, tile_opp->x+dx, tile_opp->y+dy);
1737         if (!(edge_opp->flags & F_EDGE_SET)) {
1738             solvep(("%*sSetting edge %d,%d as opposite %d,%d\n",
1739                    solver_recurse_depth*4, "",
1740                    tile_opp->x-dx, tile_opp->y-dy, edge->x, edge->y));
1741             edge_opp->flags |= F_EDGE_SET;
1742             didsth = 1;
1743         }
1744     }
1745     return didsth;
1746 }
1747
1748 static int solver_spaces_oneposs_cb(game_state *state, space *tile, void *ctx)
1749 {
1750     int n, eset, ret;
1751     space *edgeadj[4], *tileadj[4];
1752     int dotx, doty;
1753
1754     assert(tile->type == s_tile);
1755     if (tile->flags & F_TILE_ASSOC) return 0;
1756
1757     adjacencies(state, tile, edgeadj, tileadj);
1758
1759     /* Empty tile. If each edge is either set, or associated with
1760      * the same dot, we must also associate with dot. */
1761     eset = 0; dotx = -1; doty = -1;
1762     for (n = 0; n < 4; n++) {
1763         assert(edgeadj[n]);
1764         assert(edgeadj[n]->type == s_edge);
1765         if (edgeadj[n]->flags & F_EDGE_SET) {
1766             eset++;
1767         } else {
1768             assert(tileadj[n]);
1769             assert(tileadj[n]->type == s_tile);
1770
1771             /* If an adjacent tile is empty we can't make any deductions.*/
1772             if (!(tileadj[n]->flags & F_TILE_ASSOC))
1773                 return 0;
1774
1775             /* If an adjacent tile is assoc. with a different dot
1776              * we can't make any deductions. */
1777             if (dotx != -1 && doty != -1 &&
1778                 (tileadj[n]->dotx != dotx ||
1779                  tileadj[n]->doty != doty))
1780                 return 0;
1781
1782             dotx = tileadj[n]->dotx;
1783             doty = tileadj[n]->doty;
1784         }
1785     }
1786     if (eset == 4) {
1787         solvep(("%*simpossible: empty tile %d,%d has 4 edges\n",
1788                solver_recurse_depth*4, "",
1789                tile->x, tile->y));
1790         return -1;
1791     }
1792     assert(dotx != -1 && doty != -1);
1793
1794     ret = solver_add_assoc(state, tile, dotx, doty, "rest are edges");
1795     if (ret == -1) return -1;
1796     assert(ret != 0); /* really should have done something. */
1797
1798     return 1;
1799 }
1800
1801 /* Improved algorithm for tracking line-of-sight from dots, and not spaces.
1802  *
1803  * The solver_ctx already stores a list of dots: the algorithm proceeds by
1804  * expanding outwards from each dot in turn, expanding first to the boundary
1805  * of its currently-connected tile and then to all empty tiles that could see
1806  * it. Empty tiles will be flagged with a 'can see dot <x,y>' sticker.
1807  *
1808  * Expansion will happen by (symmetrically opposite) pairs of squares; if
1809  * a square hasn't an opposite number there's no point trying to expand through
1810  * it. Empty tiles will therefore also be tagged in pairs.
1811  *
1812  * If an empty tile already has a 'can see dot <x,y>' tag from a previous dot,
1813  * it (and its partner) gets untagged (or, rather, a 'can see two dots' tag)
1814  * because we're looking for single-dot possibilities.
1815  *
1816  * Once we've gone through all the dots, any which still have a 'can see dot'
1817  * tag get associated with that dot (because it must have been the only one);
1818  * any without any tag (i.e. that could see _no_ dots) cause an impossibility
1819  * marked.
1820  *
1821  * The expansion will happen each time with a stored list of (space *) pairs,
1822  * rather than a mark-and-sweep idea; that's horrifically inefficient.
1823  *
1824  * expansion algorithm:
1825  *
1826  * * allocate list of (space *) the size of s->sx*s->sy.
1827  * * allocate second grid for (flags, dotx, doty) size of sx*sy.
1828  *
1829  * clear second grid (flags = 0, all dotx and doty = 0)
1830  * flags: F_REACHABLE, F_MULTIPLE
1831  *
1832  *
1833  * * for each dot, start with one pair of tiles that are associated with it --
1834  *   * vertex --> (dx+1, dy+1), (dx-1, dy-1)
1835  *   * edge --> (adj1, adj2)
1836  *   * tile --> (tile, tile) ???
1837  * * mark that pair of tiles with F_MARK, clear all other F_MARKs.
1838  * * add two tiles to start of list.
1839  *
1840  * set start = 0, end = next = 2
1841  *
1842  * from (start to end-1, step 2) {
1843  * * we have two tiles (t1, t2), opposites wrt our dot.
1844  * * for each (at1) sensible adjacent tile to t1 (i.e. not past an edge):
1845  *   * work out at2 as the opposite to at1
1846  *   * assert at1 and at2 have the same F_MARK values.
1847  *   * if at1 & F_MARK ignore it (we've been there on a previous sweep)
1848  *   * if either are associated with a different dot
1849  *     * mark both with F_MARK (so we ignore them later)
1850  *   * otherwise (assoc. with our dot, or empty):
1851  *     * mark both with F_MARK
1852  *     * add their space * values to the end of the list, set next += 2.
1853  * }
1854  *
1855  * if (end == next)
1856  * * we didn't add any new squares; exit the loop.
1857  * else
1858  * * set start = next+1, end = next. go round again
1859  *
1860  * We've finished expanding from the dot. Now, for each square we have
1861  * in our list (--> each square with F_MARK):
1862  * * if the tile is empty:
1863  *   * if F_REACHABLE was already set
1864  *     * set F_MULTIPLE
1865  *   * otherwise
1866  *     * set F_REACHABLE, set dotx and doty to our dot.
1867  *
1868  * Then, continue the whole thing for each dot in turn.
1869  *
1870  * Once we've done for each dot, go through the entire grid looking for
1871  * empty tiles: for each empty tile:
1872    * if F_REACHABLE and not F_MULTIPLE, set that dot (and its double)
1873    * if !F_REACHABLE, return as impossible.
1874  *
1875  */
1876
1877 /* Returns 1 if this tile is either already associated with this dot,
1878  * or blank. */
1879 static int solver_expand_checkdot(space *tile, space *dot)
1880 {
1881     if (!(tile->flags & F_TILE_ASSOC)) return 1;
1882     if (tile->dotx == dot->x && tile->doty == dot->y) return 1;
1883     return 0;
1884 }
1885
1886 static void solver_expand_fromdot(game_state *state, space *dot, solver_ctx *sctx)
1887 {
1888     int i, j, x, y, start, end, next;
1889     space *sp;
1890
1891     /* Clear the grid of the (space) flags we'll use. */
1892
1893     /* This is well optimised; analysis showed that:
1894         for (i = 0; i < sctx->sz; i++) state->grid[i].flags &= ~F_MARK;
1895        took up ~85% of the total function time! */
1896     for (y = 1; y < state->sy; y += 2) {
1897         sp = &SPACE(state, 1, y);
1898         for (x = 1; x < state->sx; x += 2, sp += 2)
1899             sp->flags &= ~F_MARK;
1900     }
1901
1902     /* Seed the list of marked squares with two that must be associated
1903      * with our dot (possibly the same space) */
1904     if (dot->type == s_tile) {
1905         sctx->scratch[0] = sctx->scratch[1] = dot;
1906     } else if (dot->type == s_edge) {
1907         tiles_from_edge(state, dot, sctx->scratch);
1908     } else if (dot->type == s_vertex) {
1909         /* pick two of the opposite ones arbitrarily. */
1910         sctx->scratch[0] = &SPACE(state, dot->x-1, dot->y-1);
1911         sctx->scratch[1] = &SPACE(state, dot->x+1, dot->y+1);
1912     }
1913     assert(sctx->scratch[0]->flags & F_TILE_ASSOC);
1914     assert(sctx->scratch[1]->flags & F_TILE_ASSOC);
1915
1916     sctx->scratch[0]->flags |= F_MARK;
1917     sctx->scratch[1]->flags |= F_MARK;
1918
1919     debug(("%*sexpand from dot %d,%d seeded with %d,%d and %d,%d.\n",
1920            solver_recurse_depth*4, "", dot->x, dot->y,
1921            sctx->scratch[0]->x, sctx->scratch[0]->y,
1922            sctx->scratch[1]->x, sctx->scratch[1]->y));
1923
1924     start = 0; end = 2; next = 2;
1925
1926 expand:
1927     debug(("%*sexpand: start %d, end %d, next %d\n",
1928            solver_recurse_depth*4, "", start, end, next));
1929     for (i = start; i < end; i += 2) {
1930         space *t1 = sctx->scratch[i]/*, *t2 = sctx->scratch[i+1]*/;
1931         space *edges[4], *tileadj[4], *tileadj2;
1932
1933         adjacencies(state, t1, edges, tileadj);
1934
1935         for (j = 0; j < 4; j++) {
1936             assert(edges[j]);
1937             if (edges[j]->flags & F_EDGE_SET) continue;
1938             assert(tileadj[j]);
1939
1940             if (tileadj[j]->flags & F_MARK) continue; /* seen before. */
1941
1942             /* We have a tile adjacent to t1; find its opposite. */
1943             tileadj2 = space_opposite_dot(state, tileadj[j], dot);
1944             if (!tileadj2) {
1945                 debug(("%*sMarking %d,%d, no opposite.\n",
1946                        solver_recurse_depth*4, "",
1947                        tileadj[j]->x, tileadj[j]->y));
1948                 tileadj[j]->flags |= F_MARK;
1949                 continue; /* no opposite, so mark for next time. */
1950             }
1951             /* If the tile had an opposite we should have either seen both of
1952              * these, or neither of these, before. */
1953             assert(!(tileadj2->flags & F_MARK));
1954
1955             if (solver_expand_checkdot(tileadj[j], dot) &&
1956                 solver_expand_checkdot(tileadj2, dot)) {
1957                 /* Both tiles could associate with this dot; add them to
1958                  * our list. */
1959                 debug(("%*sAdding %d,%d and %d,%d to possibles list.\n",
1960                        solver_recurse_depth*4, "",
1961                        tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1962                 sctx->scratch[next++] = tileadj[j];
1963                 sctx->scratch[next++] = tileadj2;
1964             }
1965             /* Either way, we've seen these tiles already so mark them. */
1966             debug(("%*sMarking %d,%d and %d,%d.\n",
1967                    solver_recurse_depth*4, "",
1968                        tileadj[j]->x, tileadj[j]->y, tileadj2->x, tileadj2->y));
1969             tileadj[j]->flags |= F_MARK;
1970             tileadj2->flags |= F_MARK;
1971         }
1972     }
1973     if (next > end) {
1974         /* We added more squares; go back and try again. */
1975         start = end; end = next; goto expand;
1976     }
1977
1978     /* We've expanded as far as we can go. Now we update the main flags
1979      * on all tiles we've expanded into -- if they were empty, we have
1980      * found possible associations for this dot. */
1981     for (i = 0; i < end; i++) {
1982         if (sctx->scratch[i]->flags & F_TILE_ASSOC) continue;
1983         if (sctx->scratch[i]->flags & F_REACHABLE) {
1984             /* This is (at least) the second dot this tile could
1985              * associate with. */
1986             debug(("%*sempty tile %d,%d could assoc. other dot %d,%d\n",
1987                    solver_recurse_depth*4, "",
1988                    sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1989             sctx->scratch[i]->flags |= F_MULTIPLE;
1990         } else {
1991             /* This is the first (possibly only) dot. */
1992             debug(("%*sempty tile %d,%d could assoc. 1st dot %d,%d\n",
1993                    solver_recurse_depth*4, "",
1994                    sctx->scratch[i]->x, sctx->scratch[i]->y, dot->x, dot->y));
1995             sctx->scratch[i]->flags |= F_REACHABLE;
1996             sctx->scratch[i]->dotx = dot->x;
1997             sctx->scratch[i]->doty = dot->y;
1998         }
1999     }
2000     dbg_state(state);
2001 }
2002
2003 static int solver_expand_postcb(game_state *state, space *tile, void *ctx)
2004 {
2005     assert(tile->type == s_tile);
2006
2007     if (tile->flags & F_TILE_ASSOC) return 0;
2008
2009     if (!(tile->flags & F_REACHABLE)) {
2010         solvep(("%*simpossible: space (%d,%d) can reach no dots.\n",
2011                 solver_recurse_depth*4, "", tile->x, tile->y));
2012         return -1;
2013     }
2014     if (tile->flags & F_MULTIPLE) return 0;
2015
2016     return solver_add_assoc(state, tile, tile->dotx, tile->doty,
2017                             "single possible dot after expansion");
2018 }
2019
2020 static int solver_expand_dots(game_state *state, solver_ctx *sctx)
2021 {
2022     int i;
2023
2024     for (i = 0; i < sctx->sz; i++)
2025         state->grid[i].flags &= ~(F_REACHABLE|F_MULTIPLE);
2026
2027     for (i = 0; i < state->ndots; i++)
2028         solver_expand_fromdot(state, state->dots[i], sctx);
2029
2030     return foreach_tile(state, solver_expand_postcb, IMPOSSIBLE_QUITS, sctx);
2031 }
2032
2033 struct recurse_ctx {
2034     space *best;
2035     int bestn;
2036 };
2037
2038 static int solver_recurse_cb(game_state *state, space *tile, void *ctx)
2039 {
2040     struct recurse_ctx *rctx = (struct recurse_ctx *)ctx;
2041     int i, n = 0;
2042
2043     assert(tile->type == s_tile);
2044     if (tile->flags & F_TILE_ASSOC) return 0;
2045
2046     /* We're unassociated: count up all the dots we could associate with. */
2047     for (i = 0; i < state->ndots; i++) {
2048         if (dotfortile(state, tile, state->dots[i]))
2049             n++;
2050     }
2051     if (n > rctx->bestn) {
2052         rctx->bestn = n;
2053         rctx->best = tile;
2054     }
2055     return 0;
2056 }
2057
2058 static int solver_state(game_state *state, int maxdiff);
2059
2060 #define MAXRECURSE 5
2061
2062 static int solver_recurse(game_state *state, int maxdiff)
2063 {
2064     int diff = DIFF_IMPOSSIBLE, ret, n, gsz = state->sx * state->sy;
2065     space *ingrid, *outgrid = NULL, *bestopp;
2066     struct recurse_ctx rctx;
2067
2068     if (solver_recurse_depth >= MAXRECURSE) {
2069         solvep(("Limiting recursion to %d, returning.", MAXRECURSE));
2070         return DIFF_UNFINISHED;
2071     }
2072
2073     /* Work out the cell to recurse on; go through all unassociated tiles
2074      * and find which one has the most possible dots it could associate
2075      * with. */
2076     rctx.best = NULL;
2077     rctx.bestn = 0;
2078
2079     foreach_tile(state, solver_recurse_cb, 0, &rctx);
2080     if (rctx.bestn == 0) return DIFF_IMPOSSIBLE; /* or assert? */
2081     assert(rctx.best);
2082
2083     solvep(("%*sRecursing around %d,%d, with %d possible dots.\n",
2084            solver_recurse_depth*4, "",
2085            rctx.best->x, rctx.best->y, rctx.bestn));
2086
2087 #ifdef STANDALONE_SOLVER
2088     solver_recurse_depth++;
2089 #endif
2090
2091     ingrid = snewn(gsz, space);
2092     memcpy(ingrid, state->grid, gsz * sizeof(space));
2093
2094     for (n = 0; n < state->ndots; n++) {
2095         memcpy(state->grid, ingrid, gsz * sizeof(space));
2096
2097         if (!dotfortile(state, rctx.best, state->dots[n])) continue;
2098
2099         /* set cell (temporarily) pointing to that dot. */
2100         solver_add_assoc(state, rctx.best,
2101                          state->dots[n]->x, state->dots[n]->y,
2102                          "Attempting for recursion");
2103
2104         ret = solver_state(state, maxdiff);
2105
2106         if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE) {
2107             /* we found our first solved grid; copy it away. */
2108             assert(!outgrid);
2109             outgrid = snewn(gsz, space);
2110             memcpy(outgrid, state->grid, gsz * sizeof(space));
2111         }
2112         /* reset cell back to unassociated. */
2113         bestopp = tile_opposite(state, rctx.best);
2114         assert(bestopp && bestopp->flags & F_TILE_ASSOC);
2115
2116         remove_assoc(state, rctx.best);
2117         remove_assoc(state, bestopp);
2118
2119         if (ret == DIFF_AMBIGUOUS || ret == DIFF_UNFINISHED)
2120             diff = ret;
2121         else if (ret == DIFF_IMPOSSIBLE)
2122             /* no change */;
2123         else {
2124             /* precisely one solution */
2125             if (diff == DIFF_IMPOSSIBLE)
2126                 diff = DIFF_UNREASONABLE;
2127             else
2128                 diff = DIFF_AMBIGUOUS;
2129         }
2130         /* if we've found >1 solution, or ran out of recursion,
2131          * give up immediately. */
2132         if (diff == DIFF_AMBIGUOUS || diff == DIFF_UNFINISHED)
2133             break;
2134     }
2135
2136 #ifdef STANDALONE_SOLVER
2137     solver_recurse_depth--;
2138 #endif
2139
2140     if (outgrid) {
2141         /* we found (at least one) soln; copy it back to state */
2142         memcpy(state->grid, outgrid, gsz * sizeof(space));
2143         sfree(outgrid);
2144     }
2145     sfree(ingrid);
2146     return diff;
2147 }
2148
2149 static int solver_state(game_state *state, int maxdiff)
2150 {
2151     solver_ctx *sctx = new_solver(state);
2152     int ret, diff = DIFF_NORMAL;
2153
2154 #ifdef STANDALONE_PICTURE_GENERATOR
2155     /* hack, hack: set picture to NULL during solving so that add_assoc
2156      * won't complain when we attempt recursive guessing and guess wrong */
2157     int *savepic = picture;
2158     picture = NULL;
2159 #endif
2160
2161     ret = solver_obvious(state);
2162     if (ret < 0) {
2163         diff = DIFF_IMPOSSIBLE;
2164         goto got_result;
2165     }
2166
2167 #define CHECKRET(d) do {                                        \
2168     if (ret < 0) { diff = DIFF_IMPOSSIBLE; goto got_result; }   \
2169     if (ret > 0) { diff = max(diff, (d)); goto cont; }          \
2170 } while(0)
2171
2172     while (1) {
2173 cont:
2174         ret = foreach_edge(state, solver_lines_opposite_cb,
2175                            IMPOSSIBLE_QUITS, sctx);
2176         CHECKRET(DIFF_NORMAL);
2177
2178         ret = foreach_tile(state, solver_spaces_oneposs_cb,
2179                            IMPOSSIBLE_QUITS, sctx);
2180         CHECKRET(DIFF_NORMAL);
2181
2182         ret = solver_expand_dots(state, sctx);
2183         CHECKRET(DIFF_NORMAL);
2184
2185         if (maxdiff <= DIFF_NORMAL)
2186             break;
2187
2188         /* harder still? */
2189
2190         /* if we reach here, we've made no deductions, so we terminate. */
2191         break;
2192     }
2193
2194     if (check_complete(state, NULL, NULL)) goto got_result;
2195
2196     diff = (maxdiff >= DIFF_UNREASONABLE) ?
2197         solver_recurse(state, maxdiff) : DIFF_UNFINISHED;
2198
2199 got_result:
2200     free_solver(sctx);
2201 #ifndef STANDALONE_SOLVER
2202     debug(("solver_state ends, diff %s:\n", galaxies_diffnames[diff]));
2203     dbg_state(state);
2204 #endif
2205
2206 #ifdef STANDALONE_PICTURE_GENERATOR
2207     picture = savepic;
2208 #endif
2209
2210     return diff;
2211 }
2212
2213 #ifndef EDITOR
2214 static char *solve_game(const game_state *state, const game_state *currstate,
2215                         const char *aux, char **error)
2216 {
2217     game_state *tosolve;
2218     char *ret;
2219     int i;
2220     int diff;
2221
2222     tosolve = dup_game(currstate);
2223     diff = solver_state(tosolve, DIFF_UNREASONABLE);
2224     if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2225         debug(("solve_game solved with current state.\n"));
2226         goto solved;
2227     }
2228     free_game(tosolve);
2229
2230     tosolve = dup_game(state);
2231     diff = solver_state(tosolve, DIFF_UNREASONABLE);
2232     if (diff != DIFF_UNFINISHED && diff != DIFF_IMPOSSIBLE) {
2233         debug(("solve_game solved with original state.\n"));
2234         goto solved;
2235     }
2236     free_game(tosolve);
2237
2238     return NULL;
2239
2240 solved:
2241     /*
2242      * Clear tile associations: the solution will only include the
2243      * edges.
2244      */
2245     for (i = 0; i < tosolve->sx*tosolve->sy; i++)
2246         tosolve->grid[i].flags &= ~F_TILE_ASSOC;
2247     ret = diff_game(currstate, tosolve, 1);
2248     free_game(tosolve);
2249     return ret;
2250 }
2251 #endif
2252
2253 /* ----------------------------------------------------------
2254  * User interface.
2255  */
2256
2257 struct game_ui {
2258     int dragging;
2259     int dx, dy;         /* pixel coords of drag pos. */
2260     int dotx, doty;     /* grid coords of dot we're dragging from. */
2261     int srcx, srcy;     /* grid coords of drag start */
2262     int cur_x, cur_y, cur_visible;
2263 };
2264
2265 static game_ui *new_ui(const game_state *state)
2266 {
2267     game_ui *ui = snew(game_ui);
2268     ui->dragging = FALSE;
2269     ui->cur_x = ui->cur_y = 1;
2270     ui->cur_visible = 0;
2271     return ui;
2272 }
2273
2274 static void free_ui(game_ui *ui)
2275 {
2276     sfree(ui);
2277 }
2278
2279 static char *encode_ui(const game_ui *ui)
2280 {
2281     return NULL;
2282 }
2283
2284 static void decode_ui(game_ui *ui, const char *encoding)
2285 {
2286 }
2287
2288 static void game_changed_state(game_ui *ui, const game_state *oldstate,
2289                                const game_state *newstate)
2290 {
2291 }
2292
2293 #define FLASH_TIME 0.15F
2294
2295 #define PREFERRED_TILE_SIZE 32
2296 #define TILE_SIZE (ds->tilesize)
2297 #define DOT_SIZE        (TILE_SIZE / 4)
2298 #define EDGE_THICKNESS (max(TILE_SIZE / 16, 2))
2299 #define BORDER TILE_SIZE
2300
2301 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
2302 #define SCOORD(x) ( ((x) * TILE_SIZE)/2 + BORDER )
2303 #define FROMCOORD(x) ( ((x) - BORDER) / TILE_SIZE )
2304
2305 #define DRAW_WIDTH      (BORDER * 2 + ds->w * TILE_SIZE)
2306 #define DRAW_HEIGHT     (BORDER * 2 + ds->h * TILE_SIZE)
2307
2308 #define CURSOR_SIZE DOT_SIZE
2309
2310 struct game_drawstate {
2311     int started;
2312     int w, h;
2313     int tilesize;
2314     unsigned long *grid;
2315     int *dx, *dy;
2316     blitter *bl;
2317
2318     int dragging, dragx, dragy;
2319
2320     int *colour_scratch;
2321
2322     int cx, cy, cur_visible;
2323     blitter *cur_bl;
2324 };
2325
2326 #define CORNER_TOLERANCE 0.15F
2327 #define CENTRE_TOLERANCE 0.15F
2328
2329 /*
2330  * Round FP coordinates to the centre of the nearest edge.
2331  */
2332 #ifndef EDITOR
2333 static void coord_round_to_edge(float x, float y, int *xr, int *yr)
2334 {
2335     float xs, ys, xv, yv, dx, dy;
2336
2337     /*
2338      * Find the nearest square-centre.
2339      */
2340     xs = (float)floor(x) + 0.5F;
2341     ys = (float)floor(y) + 0.5F;
2342
2343     /*
2344      * Find the nearest grid vertex.
2345      */
2346     xv = (float)floor(x + 0.5F);
2347     yv = (float)floor(y + 0.5F);
2348
2349     /*
2350      * Determine whether the horizontal or vertical edge from that
2351      * vertex alongside that square is closer to us, by comparing
2352      * distances from the square cente.
2353      */
2354     dx = (float)fabs(x - xs);
2355     dy = (float)fabs(y - ys);
2356     if (dx > dy) {
2357         /* Vertical edge: x-coord of corner,
2358          * y-coord of square centre. */
2359         *xr = 2 * (int)xv;
2360         *yr = 1 + 2 * (int)floor(ys);
2361     } else {
2362         /* Horizontal edge: x-coord of square centre,
2363          * y-coord of corner. */
2364         *xr = 1 + 2 * (int)floor(xs);
2365         *yr = 2 * (int)yv;
2366     }
2367 }
2368 #endif
2369
2370 #ifdef EDITOR
2371 static char *interpret_move(const game_state *state, game_ui *ui,
2372                             const game_drawstate *ds,
2373                             int x, int y, int button)
2374 {
2375     char buf[80];
2376     int px, py;
2377     space *sp;
2378
2379     px = 2*FROMCOORD((float)x) + 0.5;
2380     py = 2*FROMCOORD((float)y) + 0.5;
2381
2382     state->cdiff = -1;
2383
2384     if (button == 'C' || button == 'c') return dupstr("C");
2385
2386     if (button == 'S' || button == 's') {
2387         char *ret;
2388         game_state *tmp = dup_game(state);
2389         state->cdiff = solver_state(tmp, DIFF_UNREASONABLE-1);
2390         ret = diff_game(state, tmp, 0);
2391         free_game(tmp);
2392         return ret;
2393     }
2394
2395     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
2396         if (!INUI(state, px, py)) return NULL;
2397         sp = &SPACE(state, px, py);
2398         if (!dot_is_possible(state, sp, 1)) return NULL;
2399         sprintf(buf, "%c%d,%d",
2400                 (char)((button == LEFT_BUTTON) ? 'D' : 'd'), px, py);
2401         return dupstr(buf);
2402     }
2403
2404     return NULL;
2405 }
2406 #else
2407 static char *interpret_move(const game_state *state, game_ui *ui,
2408                             const game_drawstate *ds,
2409                             int x, int y, int button)
2410 {
2411     /* UI operations (play mode):
2412      *
2413      * Toggle edge (set/unset) (left-click on edge)
2414      * Associate space with dot (left-drag from dot)
2415      * Unassociate space (left-drag from space off grid)
2416      * Autofill lines around shape? (right-click?)
2417      *
2418      * (edit mode; will clear all lines/associations)
2419      *
2420      * Add or remove dot (left-click)
2421      */
2422     char buf[80];
2423     const char *sep = "";
2424     int px, py;
2425     space *sp, *dot;
2426
2427     buf[0] = '\0';
2428
2429     if (button == 'H' || button == 'h') {
2430         char *ret;
2431         game_state *tmp = dup_game(state);
2432         solver_obvious(tmp);
2433         ret = diff_game(state, tmp, 0);
2434         free_game(tmp);
2435         return ret;
2436     }
2437
2438     if (button == LEFT_BUTTON) {
2439         ui->cur_visible = 0;
2440         coord_round_to_edge(FROMCOORD((float)x), FROMCOORD((float)y),
2441                             &px, &py);
2442
2443         if (!INUI(state, px, py)) return NULL;
2444
2445         sp = &SPACE(state, px, py);
2446         assert(sp->type == s_edge);
2447         {
2448             sprintf(buf, "E%d,%d", px, py);
2449             return dupstr(buf);
2450         }
2451     } else if (button == RIGHT_BUTTON) {
2452         int px1, py1;
2453
2454         ui->cur_visible = 0;
2455
2456         px = (int)(2*FROMCOORD((float)x) + 0.5);
2457         py = (int)(2*FROMCOORD((float)y) + 0.5);
2458
2459         dot = NULL;
2460
2461         /*
2462          * If there's a dot anywhere nearby, we pick up an arrow
2463          * pointing at that dot.
2464          */
2465         for (py1 = py-1; py1 <= py+1; py1++)
2466             for (px1 = px-1; px1 <= px+1; px1++) {
2467                 if (px1 >= 0 && px1 < state->sx &&
2468                     py1 >= 0 && py1 < state->sy &&
2469                     x >= SCOORD(px1-1) && x < SCOORD(px1+1) &&
2470                     y >= SCOORD(py1-1) && y < SCOORD(py1+1) &&
2471                     SPACE(state, px1, py1).flags & F_DOT) {
2472                     /*
2473                      * Found a dot. Begin a drag from it.
2474                      */
2475                     dot = &SPACE(state, px1, py1);
2476                     ui->srcx = px1;
2477                     ui->srcy = py1;
2478                     goto done;         /* multi-level break */
2479                 }
2480             }
2481
2482         /*
2483          * Otherwise, find the nearest _square_, and pick up the
2484          * same arrow as it's got on it, if any.
2485          */
2486         if (!dot) {
2487             px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2488             py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2489             if (px >= 0 && px < state->sx && py >= 0 && py < state->sy) {
2490                 sp = &SPACE(state, px, py);
2491                 if (sp->flags & F_TILE_ASSOC) {
2492                     dot = &SPACE(state, sp->dotx, sp->doty);
2493                     ui->srcx = px;
2494                     ui->srcy = py;
2495                 }
2496             }
2497         }
2498
2499         done:
2500         /*
2501          * Now, if we've managed to find a dot, begin a drag.
2502          */
2503         if (dot) {
2504             ui->dragging = TRUE;
2505             ui->dx = x;
2506             ui->dy = y;
2507             ui->dotx = dot->x;
2508             ui->doty = dot->y;
2509             return "";
2510         }
2511     } else if (button == RIGHT_DRAG && ui->dragging) {
2512         /* just move the drag coords. */
2513         ui->dx = x;
2514         ui->dy = y;
2515         return "";
2516     } else if (button == RIGHT_RELEASE && ui->dragging) {
2517         ui->dragging = FALSE;
2518
2519         /*
2520          * Drags are always targeted at a single square.
2521          */
2522         px = 2*FROMCOORD(x+TILE_SIZE) - 1;
2523         py = 2*FROMCOORD(y+TILE_SIZE) - 1;
2524
2525         /*
2526          * Dragging an arrow on to the same square it started from
2527          * is a null move; just update the ui and finish.
2528          */
2529         if (px == ui->srcx && py == ui->srcy)
2530             return "";
2531
2532         /*
2533          * Otherwise, we remove the arrow from its starting
2534          * square if we didn't start from a dot...
2535          */
2536         if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2537             SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2538             sprintf(buf + strlen(buf), "%sU%d,%d", sep, ui->srcx, ui->srcy);
2539             sep = ";";
2540         }
2541
2542         /*
2543          * ... and if the square we're moving it _to_ is valid, we
2544          * add one there instead.
2545          */
2546         if (INUI(state, px, py)) {
2547             sp = &SPACE(state, px, py);
2548
2549             if (!(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC))
2550                 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2551                         sep, px, py, ui->dotx, ui->doty);
2552         }
2553
2554         if (buf[0])
2555             return dupstr(buf);
2556         else
2557             return "";
2558     } else if (IS_CURSOR_MOVE(button)) {
2559         move_cursor(button, &ui->cur_x, &ui->cur_y, state->sx-1, state->sy-1, 0);
2560         if (ui->cur_x < 1) ui->cur_x = 1;
2561         if (ui->cur_y < 1) ui->cur_y = 1;
2562         ui->cur_visible = 1;
2563         if (ui->dragging) {
2564             ui->dx = SCOORD(ui->cur_x);
2565             ui->dy = SCOORD(ui->cur_y);
2566         }
2567         return "";
2568     } else if (IS_CURSOR_SELECT(button)) {
2569         if (!ui->cur_visible) {
2570             ui->cur_visible = 1;
2571             return "";
2572         }
2573         sp = &SPACE(state, ui->cur_x, ui->cur_y);
2574         if (ui->dragging) {
2575             ui->dragging = FALSE;
2576
2577             if ((ui->srcx != ui->dotx || ui->srcy != ui->doty) &&
2578                 SPACE(state, ui->srcx, ui->srcy).flags & F_TILE_ASSOC) {
2579                 sprintf(buf, "%sU%d,%d", sep, ui->srcx, ui->srcy);
2580                 sep = ";";
2581             }
2582             if (sp->type == s_tile && !(sp->flags & F_DOT) && !(sp->flags & F_TILE_ASSOC)) {
2583                 sprintf(buf + strlen(buf), "%sA%d,%d,%d,%d",
2584                         sep, ui->cur_x, ui->cur_y, ui->dotx, ui->doty);
2585             }
2586             return dupstr(buf);
2587         } else if (sp->flags & F_DOT) {
2588             ui->dragging = TRUE;
2589             ui->dx = SCOORD(ui->cur_x);
2590             ui->dy = SCOORD(ui->cur_y);
2591             ui->dotx = ui->srcx = ui->cur_x;
2592             ui->doty = ui->srcy = ui->cur_y;
2593             return "";
2594         } else if (sp->flags & F_TILE_ASSOC) {
2595             assert(sp->type == s_tile);
2596             ui->dragging = TRUE;
2597             ui->dx = SCOORD(ui->cur_x);
2598             ui->dy = SCOORD(ui->cur_y);
2599             ui->dotx = sp->dotx;
2600             ui->doty = sp->doty;
2601             ui->srcx = ui->cur_x;
2602             ui->srcy = ui->cur_y;
2603             return "";
2604         } else if (sp->type == s_edge) {
2605             sprintf(buf, "E%d,%d", ui->cur_x, ui->cur_y);
2606             return dupstr(buf);
2607         }
2608     }
2609
2610     return NULL;
2611 }
2612 #endif
2613
2614 static int check_complete(const game_state *state, int *dsf, int *colours)
2615 {
2616     int w = state->w, h = state->h;
2617     int x, y, i, ret;
2618
2619     int free_dsf;
2620     struct sqdata {
2621         int minx, miny, maxx, maxy;
2622         int cx, cy;
2623         int valid, colour;
2624     } *sqdata;
2625
2626     if (!dsf) {
2627         dsf = snew_dsf(w*h);
2628         free_dsf = TRUE;
2629     } else {
2630         dsf_init(dsf, w*h);
2631         free_dsf = FALSE;
2632     }
2633
2634     /*
2635      * During actual game play, completion checking is done on the
2636      * basis of the edges rather than the square associations. So
2637      * first we must go through the grid figuring out the connected
2638      * components into which the edges divide it.
2639      */
2640     for (y = 0; y < h; y++)
2641         for (x = 0; x < w; x++) {
2642             if (y+1 < h && !(SPACE(state, 2*x+1, 2*y+2).flags & F_EDGE_SET))
2643                 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2644             if (x+1 < w && !(SPACE(state, 2*x+2, 2*y+1).flags & F_EDGE_SET))
2645                 dsf_merge(dsf, y*w+x, y*w+(x+1));
2646         }
2647
2648     /*
2649      * That gives us our connected components. Now, for each
2650      * component, decide whether it's _valid_. A valid component is
2651      * one which:
2652      *
2653      *  - is 180-degree rotationally symmetric
2654      *  - has a dot at its centre of symmetry
2655      *  - has no other dots anywhere within it (including on its
2656      *    boundary)
2657      *  - contains no internal edges (i.e. edges separating two
2658      *    squares which are both part of the component).
2659      */
2660
2661     /*
2662      * First, go through the grid finding the bounding box of each
2663      * component.
2664      */
2665     sqdata = snewn(w*h, struct sqdata);
2666     for (i = 0; i < w*h; i++) {
2667         sqdata[i].minx = w+1;
2668         sqdata[i].miny = h+1;
2669         sqdata[i].maxx = sqdata[i].maxy = -1;
2670         sqdata[i].valid = FALSE;
2671     }
2672     for (y = 0; y < h; y++)
2673         for (x = 0; x < w; x++) {
2674             i = dsf_canonify(dsf, y*w+x);
2675             if (sqdata[i].minx > x)
2676                 sqdata[i].minx = x;
2677             if (sqdata[i].maxx < x)
2678                 sqdata[i].maxx = x;
2679             if (sqdata[i].miny > y)
2680                 sqdata[i].miny = y;
2681             if (sqdata[i].maxy < y)
2682                 sqdata[i].maxy = y;
2683             sqdata[i].valid = TRUE;
2684         }
2685
2686     /*
2687      * Now we're in a position to loop over each actual component
2688      * and figure out where its centre of symmetry has to be if
2689      * it's anywhere.
2690      */
2691     for (i = 0; i < w*h; i++)
2692         if (sqdata[i].valid) {
2693             int cx, cy;
2694             cx = sqdata[i].cx = sqdata[i].minx + sqdata[i].maxx + 1;
2695             cy = sqdata[i].cy = sqdata[i].miny + sqdata[i].maxy + 1;
2696             if (!(SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT))
2697                 sqdata[i].valid = FALSE;   /* no dot at centre of symmetry */
2698             if (dsf_canonify(dsf, (cy-1)/2*w+(cx-1)/2) != i ||
2699                 dsf_canonify(dsf, (cy)/2*w+(cx-1)/2) != i ||
2700                 dsf_canonify(dsf, (cy-1)/2*w+(cx)/2) != i ||
2701                 dsf_canonify(dsf, (cy)/2*w+(cx)/2) != i)
2702                 sqdata[i].valid = FALSE;   /* dot at cx,cy isn't ours */
2703             if (SPACE(state, sqdata[i].cx, sqdata[i].cy).flags & F_DOT_BLACK)
2704                 sqdata[i].colour = 2;
2705             else
2706                 sqdata[i].colour = 1;
2707         }
2708
2709     /*
2710      * Now we loop over the whole grid again, this time finding
2711      * extraneous dots (any dot which wholly or partially overlaps
2712      * a square and is not at the centre of symmetry of that
2713      * square's component disqualifies the component from validity)
2714      * and extraneous edges (any edge separating two squares
2715      * belonging to the same component also disqualifies that
2716      * component).
2717      */
2718     for (y = 1; y < state->sy-1; y++)
2719         for (x = 1; x < state->sx-1; x++) {
2720             space *sp = &SPACE(state, x, y);
2721
2722             if (sp->flags & F_DOT) {
2723                 /*
2724                  * There's a dot here. Use it to disqualify any
2725                  * component which deserves it.
2726                  */
2727                 int cx, cy;
2728                 for (cy = (y-1) >> 1; cy <= y >> 1; cy++)
2729                     for (cx = (x-1) >> 1; cx <= x >> 1; cx++) {
2730                         i = dsf_canonify(dsf, cy*w+cx);
2731                         if (x != sqdata[i].cx || y != sqdata[i].cy)
2732                             sqdata[i].valid = FALSE;
2733                     }
2734             }
2735
2736             if (sp->flags & F_EDGE_SET) {
2737                 /*
2738                  * There's an edge here. Use it to disqualify a
2739                  * component if necessary.
2740                  */
2741                 int cx1 = (x-1) >> 1, cx2 = x >> 1;
2742                 int cy1 = (y-1) >> 1, cy2 = y >> 1;
2743                 assert((cx1==cx2) ^ (cy1==cy2));
2744                 i = dsf_canonify(dsf, cy1*w+cx1);
2745                 if (i == dsf_canonify(dsf, cy2*w+cx2))
2746                     sqdata[i].valid = FALSE;
2747             }
2748         }
2749
2750     /*
2751      * And finally we test rotational symmetry: for each square in
2752      * the grid, find which component it's in, test that that
2753      * component also has a square in the symmetric position, and
2754      * disqualify it if it doesn't.
2755      */
2756     for (y = 0; y < h; y++)
2757         for (x = 0; x < w; x++) {
2758             int x2, y2;
2759
2760             i = dsf_canonify(dsf, y*w+x);
2761
2762             x2 = sqdata[i].cx - 1 - x;
2763             y2 = sqdata[i].cy - 1 - y;
2764             if (i != dsf_canonify(dsf, y2*w+x2))
2765                 sqdata[i].valid = FALSE;
2766         }
2767
2768     /*
2769      * That's it. We now have all the connected components marked
2770      * as valid or not valid. So now we return a `colours' array if
2771      * we were asked for one, and also we return an overall
2772      * true/false value depending on whether _every_ square in the
2773      * grid is part of a valid component.
2774      */
2775     ret = TRUE;
2776     for (i = 0; i < w*h; i++) {
2777         int ci = dsf_canonify(dsf, i);
2778         int thisok = sqdata[ci].valid;
2779         if (colours)
2780             colours[i] = thisok ? sqdata[ci].colour : 0;
2781         ret = ret && thisok;
2782     }
2783
2784     sfree(sqdata);
2785     if (free_dsf)
2786         sfree(dsf);
2787
2788     return ret;
2789 }
2790
2791 static game_state *execute_move(const game_state *state, const char *move)
2792 {
2793     int x, y, ax, ay, n, dx, dy;
2794     game_state *ret = dup_game(state);
2795     space *sp, *dot;
2796
2797     debug(("%s\n", move));
2798
2799     while (*move) {
2800         char c = *move;
2801         if (c == 'E' || c == 'U' || c == 'M'
2802 #ifdef EDITOR
2803             || c == 'D' || c == 'd'
2804 #endif
2805             ) {
2806             move++;
2807             if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
2808                 !INUI(ret, x, y))
2809                 goto badmove;
2810
2811             sp = &SPACE(ret, x, y);
2812 #ifdef EDITOR
2813             if (c == 'D' || c == 'd') {
2814                 unsigned int currf, newf, maskf;
2815
2816                 if (!dot_is_possible(ret, sp, 1)) goto badmove;
2817
2818                 newf = F_DOT | (c == 'd' ? F_DOT_BLACK : 0);
2819                 currf = GRID(ret, grid, x, y).flags;
2820                 maskf = F_DOT | F_DOT_BLACK;
2821                 /* if we clicked 'white dot':
2822                  *   white --> empty, empty --> white, black --> white.
2823                  * if we clicked 'black dot':
2824                  *   black --> empty, empty --> black, white --> black.
2825                  */
2826                 if (currf & maskf) {
2827                     sp->flags &= ~maskf;
2828                     if ((currf & maskf) != newf)
2829                         sp->flags |= newf;
2830                 } else
2831                     sp->flags |= newf;
2832                 sp->nassoc = 0; /* edit-mode disallows associations. */
2833                 game_update_dots(ret);
2834             } else
2835 #endif
2836                    if (c == 'E') {
2837                 if (sp->type != s_edge) goto badmove;
2838                 sp->flags ^= F_EDGE_SET;
2839             } else if (c == 'U') {
2840                 if (sp->type != s_tile || !(sp->flags & F_TILE_ASSOC))
2841                     goto badmove;
2842                 remove_assoc(ret, sp);
2843             } else if (c == 'M') {
2844                 if (!(sp->flags & F_DOT)) goto badmove;
2845                 sp->flags ^= F_DOT_HOLD;
2846             }
2847             move += n;
2848         } else if (c == 'A' || c == 'a') {
2849             move++;
2850             if (sscanf(move, "%d,%d,%d,%d%n", &x, &y, &ax, &ay, &n) != 4 ||
2851                 x < 1 || y < 1 || x >= (ret->sx-1) || y >= (ret->sy-1) ||
2852                 ax < 1 || ay < 1 || ax >= (ret->sx-1) || ay >= (ret->sy-1))
2853                 goto badmove;
2854
2855             dot = &GRID(ret, grid, ax, ay);
2856             if (!(dot->flags & F_DOT))goto badmove;
2857             if (dot->flags & F_DOT_HOLD) goto badmove;
2858
2859             for (dx = -1; dx <= 1; dx++) {
2860                 for (dy = -1; dy <= 1; dy++) {
2861                     sp = &GRID(ret, grid, x+dx, y+dy);
2862                     if (sp->type != s_tile) continue;
2863                     if (sp->flags & F_TILE_ASSOC) {
2864                         space *dot = &SPACE(ret, sp->dotx, sp->doty);
2865                         if (dot->flags & F_DOT_HOLD) continue;
2866                     }
2867                     add_assoc(ret, sp, dot);
2868                 }
2869             }
2870             move += n;
2871 #ifdef EDITOR
2872         } else if (c == 'C') {
2873             move++;
2874             clear_game(ret, 1);
2875 #endif
2876         } else if (c == 'S') {
2877             move++;
2878             ret->used_solve = 1;
2879         } else
2880             goto badmove;
2881
2882         if (*move == ';')
2883             move++;
2884         else if (*move)
2885             goto badmove;
2886     }
2887     if (check_complete(ret, NULL, NULL))
2888         ret->completed = 1;
2889     return ret;
2890
2891 badmove:
2892     free_game(ret);
2893     return NULL;
2894 }
2895
2896 /* ----------------------------------------------------------------------
2897  * Drawing routines.
2898  */
2899
2900 /* Lines will be much smaller size than squares; say, 1/8 the size?
2901  *
2902  * Need a 'top-left corner of location XxY' to take this into account;
2903  * alternaticaly, that could give the middle of that location, and the
2904  * drawing code would just know the expected dimensions.
2905  *
2906  * We also need something to take a click and work out what it was
2907  * we were interested in. Clicking on vertices is required because
2908  * we may want to drag from them, for example.
2909  */
2910
2911 static void game_compute_size(const game_params *params, int sz,
2912                               int *x, int *y)
2913 {
2914     struct { int tilesize, w, h; } ads, *ds = &ads;
2915
2916     ds->tilesize = sz;
2917     ds->w = params->w;
2918     ds->h = params->h;
2919
2920     *x = DRAW_WIDTH;
2921     *y = DRAW_HEIGHT;
2922 }
2923
2924 static void game_set_size(drawing *dr, game_drawstate *ds,
2925                           const game_params *params, int sz)
2926 {
2927     ds->tilesize = sz;
2928
2929     assert(TILE_SIZE > 0);
2930
2931     assert(!ds->bl);
2932     ds->bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2933
2934     assert(!ds->cur_bl);
2935     ds->cur_bl = blitter_new(dr, TILE_SIZE, TILE_SIZE);
2936 }
2937
2938 static float *game_colours(frontend *fe, int *ncolours)
2939 {
2940     float *ret = snewn(3 * NCOLOURS, float);
2941     int i;
2942
2943     /*
2944      * We call game_mkhighlight to ensure the background colour
2945      * isn't completely white. We don't actually use the high- and
2946      * lowlight colours it generates.
2947      */
2948     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_WHITEBG, COL_BLACKBG);
2949
2950     for (i = 0; i < 3; i++) {
2951         /*
2952          * Currently, white dots and white-background squares are
2953          * both pure white.
2954          */
2955         ret[COL_WHITEDOT * 3 + i] = 1.0F;
2956         ret[COL_WHITEBG * 3 + i] = 1.0F;
2957
2958         /*
2959          * But black-background squares are a dark grey, whereas
2960          * black dots are really black.
2961          */
2962         ret[COL_BLACKDOT * 3 + i] = 0.0F;
2963         ret[COL_BLACKBG * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.3F;
2964
2965         /*
2966          * In unfilled squares, we draw a faint gridwork.
2967          */
2968         ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] * 0.8F;
2969
2970         /*
2971          * Edges and arrows are filled in in pure black.
2972          */
2973         ret[COL_EDGE * 3 + i] = 0.0F;
2974         ret[COL_ARROW * 3 + i] = 0.0F;
2975     }
2976
2977 #ifdef EDITOR
2978     /* tinge the edit background to bluey */
2979     ret[COL_BACKGROUND * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2980     ret[COL_BACKGROUND * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2981     ret[COL_BACKGROUND * 3 + 2] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2982 #endif
2983
2984     ret[COL_CURSOR * 3 + 0] = min(ret[COL_BACKGROUND * 3 + 0] * 1.4F, 1.0F);
2985     ret[COL_CURSOR * 3 + 1] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2986     ret[COL_CURSOR * 3 + 2] = ret[COL_BACKGROUND * 3 + 0] * 0.8F;
2987
2988     *ncolours = NCOLOURS;
2989     return ret;
2990 }
2991
2992 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2993 {
2994     struct game_drawstate *ds = snew(struct game_drawstate);
2995     int i;
2996
2997     ds->started = 0;
2998     ds->w = state->w;
2999     ds->h = state->h;
3000
3001     ds->grid = snewn(ds->w*ds->h, unsigned long);
3002     for (i = 0; i < ds->w*ds->h; i++)
3003         ds->grid[i] = 0xFFFFFFFFUL;
3004     ds->dx = snewn(ds->w*ds->h, int);
3005     ds->dy = snewn(ds->w*ds->h, int);
3006
3007     ds->bl = NULL;
3008     ds->dragging = FALSE;
3009     ds->dragx = ds->dragy = 0;
3010
3011     ds->colour_scratch = snewn(ds->w * ds->h, int);
3012
3013     ds->cur_bl = NULL;
3014     ds->cx = ds->cy = 0;
3015     ds->cur_visible = 0;
3016
3017     return ds;
3018 }
3019
3020 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
3021 {
3022     if (ds->cur_bl) blitter_free(dr, ds->cur_bl);
3023     sfree(ds->colour_scratch);
3024     if (ds->bl) blitter_free(dr, ds->bl);
3025     sfree(ds->dx);
3026     sfree(ds->dy);
3027     sfree(ds->grid);
3028     sfree(ds);
3029 }
3030
3031 #define DRAW_EDGE_L    0x0001
3032 #define DRAW_EDGE_R    0x0002
3033 #define DRAW_EDGE_U    0x0004
3034 #define DRAW_EDGE_D    0x0008
3035 #define DRAW_CORNER_UL 0x0010
3036 #define DRAW_CORNER_UR 0x0020
3037 #define DRAW_CORNER_DL 0x0040
3038 #define DRAW_CORNER_DR 0x0080
3039 #define DRAW_WHITE     0x0100
3040 #define DRAW_BLACK     0x0200
3041 #define DRAW_ARROW     0x0400
3042 #define DRAW_CURSOR    0x0800
3043 #define DOT_SHIFT_C    12
3044 #define DOT_SHIFT_M    2
3045 #define DOT_WHITE      1UL
3046 #define DOT_BLACK      2UL
3047
3048 /*
3049  * Draw an arrow centred on (cx,cy), pointing in the direction
3050  * (ddx,ddy). (I.e. pointing at the point (cx+ddx, cy+ddy).
3051  */
3052 static void draw_arrow(drawing *dr, game_drawstate *ds,
3053                        int cx, int cy, int ddx, int ddy, int col)
3054 {
3055     float vlen = (float)sqrt(ddx*ddx+ddy*ddy);
3056     float xdx = ddx/vlen, xdy = ddy/vlen;
3057     float ydx = -xdy, ydy = xdx;
3058     int e1x = cx + (int)(xdx*TILE_SIZE/3), e1y = cy + (int)(xdy*TILE_SIZE/3);
3059     int e2x = cx - (int)(xdx*TILE_SIZE/3), e2y = cy - (int)(xdy*TILE_SIZE/3);
3060     int adx = (int)((ydx-xdx)*TILE_SIZE/8), ady = (int)((ydy-xdy)*TILE_SIZE/8);
3061     int adx2 = (int)((-ydx-xdx)*TILE_SIZE/8), ady2 = (int)((-ydy-xdy)*TILE_SIZE/8);
3062
3063     draw_line(dr, e1x, e1y, e2x, e2y, col);
3064     draw_line(dr, e1x, e1y, e1x+adx, e1y+ady, col);
3065     draw_line(dr, e1x, e1y, e1x+adx2, e1y+ady2, col);
3066 }
3067
3068 static void draw_square(drawing *dr, game_drawstate *ds, int x, int y,
3069                         unsigned long flags, int ddx, int ddy)
3070 {
3071     int lx = COORD(x), ly = COORD(y);
3072     int dx, dy;
3073     int gridcol;
3074
3075     clip(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3076
3077     /*
3078      * Draw the tile background.
3079      */
3080     draw_rect(dr, lx, ly, TILE_SIZE, TILE_SIZE,
3081               (flags & DRAW_WHITE ? COL_WHITEBG :
3082                flags & DRAW_BLACK ? COL_BLACKBG : COL_BACKGROUND));
3083
3084     /*
3085      * Draw the grid.
3086      */
3087     gridcol = (flags & DRAW_BLACK ? COL_BLACKDOT : COL_GRID);
3088     draw_rect(dr, lx, ly, 1, TILE_SIZE, gridcol);
3089     draw_rect(dr, lx, ly, TILE_SIZE, 1, gridcol);
3090
3091     /*
3092      * Draw the arrow, if present, or the cursor, if here.
3093      */
3094     if (flags & DRAW_ARROW)
3095         draw_arrow(dr, ds, lx + TILE_SIZE/2, ly + TILE_SIZE/2, ddx, ddy,
3096                    (flags & DRAW_CURSOR) ? COL_CURSOR : COL_ARROW);
3097     else if (flags & DRAW_CURSOR)
3098         draw_rect_outline(dr,
3099                           lx + TILE_SIZE/2 - CURSOR_SIZE,
3100                           ly + TILE_SIZE/2 - CURSOR_SIZE,
3101                           2*CURSOR_SIZE+1, 2*CURSOR_SIZE+1,
3102                           COL_CURSOR);
3103
3104     /*
3105      * Draw the edges.
3106      */
3107     if (flags & DRAW_EDGE_L)
3108         draw_rect(dr, lx, ly, EDGE_THICKNESS, TILE_SIZE, COL_EDGE);
3109     if (flags & DRAW_EDGE_R)
3110         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3111                   EDGE_THICKNESS - 1, TILE_SIZE, COL_EDGE);
3112     if (flags & DRAW_EDGE_U)
3113         draw_rect(dr, lx, ly, TILE_SIZE, EDGE_THICKNESS, COL_EDGE);
3114     if (flags & DRAW_EDGE_D)
3115         draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3116                   TILE_SIZE, EDGE_THICKNESS - 1, COL_EDGE);
3117     if (flags & DRAW_CORNER_UL)
3118         draw_rect(dr, lx, ly, EDGE_THICKNESS, EDGE_THICKNESS, COL_EDGE);
3119     if (flags & DRAW_CORNER_UR)
3120         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1, ly,
3121                   EDGE_THICKNESS - 1, EDGE_THICKNESS, COL_EDGE);
3122     if (flags & DRAW_CORNER_DL)
3123         draw_rect(dr, lx, ly + TILE_SIZE - EDGE_THICKNESS + 1,
3124                   EDGE_THICKNESS, EDGE_THICKNESS - 1, COL_EDGE);
3125     if (flags & DRAW_CORNER_DR)
3126         draw_rect(dr, lx + TILE_SIZE - EDGE_THICKNESS + 1,
3127                   ly + TILE_SIZE - EDGE_THICKNESS + 1,
3128                   EDGE_THICKNESS - 1, EDGE_THICKNESS - 1, COL_EDGE);
3129
3130     /*
3131      * Draw the dots.
3132      */
3133     for (dy = 0; dy < 3; dy++)
3134         for (dx = 0; dx < 3; dx++) {
3135             int dotval = (flags >> (DOT_SHIFT_C + DOT_SHIFT_M*(dy*3+dx)));
3136             dotval &= (1 << DOT_SHIFT_M)-1;
3137
3138             if (dotval)
3139                 draw_circle(dr, lx+dx*TILE_SIZE/2, ly+dy*TILE_SIZE/2,
3140                             DOT_SIZE,
3141                             (dotval == 1 ? COL_WHITEDOT : COL_BLACKDOT),
3142                             COL_BLACKDOT);
3143         }
3144
3145     unclip(dr);
3146     draw_update(dr, lx, ly, TILE_SIZE, TILE_SIZE);
3147 }
3148
3149 static void game_redraw(drawing *dr, game_drawstate *ds,
3150                         const game_state *oldstate, const game_state *state,
3151                         int dir, const game_ui *ui,
3152                         float animtime, float flashtime)
3153 {
3154     int w = ds->w, h = ds->h;
3155     int x, y, flashing = FALSE;
3156
3157     if (flashtime > 0) {
3158         int frame = (int)(flashtime / FLASH_TIME);
3159         flashing = (frame % 2 == 0);
3160     }
3161
3162     if (ds->dragging) {
3163         assert(ds->bl);
3164         blitter_load(dr, ds->bl, ds->dragx, ds->dragy);
3165         draw_update(dr, ds->dragx, ds->dragy, TILE_SIZE, TILE_SIZE);
3166         ds->dragging = FALSE;
3167     }
3168     if (ds->cur_visible) {
3169         assert(ds->cur_bl);
3170         blitter_load(dr, ds->cur_bl, ds->cx, ds->cy);
3171         draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3172         ds->cur_visible = FALSE;
3173     }
3174
3175     if (!ds->started) {
3176         draw_rect(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT, COL_BACKGROUND);
3177         draw_rect(dr, BORDER - EDGE_THICKNESS + 1, BORDER - EDGE_THICKNESS + 1,
3178                   w*TILE_SIZE + EDGE_THICKNESS*2 - 1,
3179                   h*TILE_SIZE + EDGE_THICKNESS*2 - 1, COL_EDGE);
3180         draw_update(dr, 0, 0, DRAW_WIDTH, DRAW_HEIGHT);
3181         ds->started = TRUE;
3182     }
3183
3184     check_complete(state, NULL, ds->colour_scratch);
3185
3186     for (y = 0; y < h; y++)
3187         for (x = 0; x < w; x++) {
3188             unsigned long flags = 0;
3189             int ddx = 0, ddy = 0;
3190             space *sp;
3191             int dx, dy;
3192
3193             /*
3194              * Set up the flags for this square. Firstly, see if we
3195              * have edges.
3196              */
3197             if (SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3198                 flags |= DRAW_EDGE_L;
3199             if (SPACE(state, x*2+2, y*2+1).flags & F_EDGE_SET)
3200                 flags |= DRAW_EDGE_R;
3201             if (SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3202                 flags |= DRAW_EDGE_U;
3203             if (SPACE(state, x*2+1, y*2+2).flags & F_EDGE_SET)
3204                 flags |= DRAW_EDGE_D;
3205
3206             /*
3207              * Also, mark corners of neighbouring edges.
3208              */
3209             if ((x > 0 && SPACE(state, x*2-1, y*2).flags & F_EDGE_SET) ||
3210                 (y > 0 && SPACE(state, x*2, y*2-1).flags & F_EDGE_SET))
3211                 flags |= DRAW_CORNER_UL;
3212             if ((x+1 < w && SPACE(state, x*2+3, y*2).flags & F_EDGE_SET) ||
3213                 (y > 0 && SPACE(state, x*2+2, y*2-1).flags & F_EDGE_SET))
3214                 flags |= DRAW_CORNER_UR;
3215             if ((x > 0 && SPACE(state, x*2-1, y*2+2).flags & F_EDGE_SET) ||
3216                 (y+1 < h && SPACE(state, x*2, y*2+3).flags & F_EDGE_SET))
3217                 flags |= DRAW_CORNER_DL;
3218             if ((x+1 < w && SPACE(state, x*2+3, y*2+2).flags & F_EDGE_SET) ||
3219                 (y+1 < h && SPACE(state, x*2+2, y*2+3).flags & F_EDGE_SET))
3220                 flags |= DRAW_CORNER_DR;
3221
3222             /*
3223              * If this square is part of a valid region, paint it
3224              * that region's colour. Exception: if we're flashing,
3225              * everything goes briefly back to background colour.
3226              */
3227             sp = &SPACE(state, x*2+1, y*2+1);
3228             if (ds->colour_scratch[y*w+x] && !flashing) {
3229                 flags |= (ds->colour_scratch[y*w+x] == 2 ?
3230                           DRAW_BLACK : DRAW_WHITE);
3231             }
3232
3233             /*
3234              * If this square is associated with a dot but it isn't
3235              * part of a valid region, draw an arrow in it pointing
3236              * in the direction of that dot.
3237              * 
3238              * Exception: if this is the source point of an active
3239              * drag, we don't draw the arrow.
3240              */
3241             if ((sp->flags & F_TILE_ASSOC) && !ds->colour_scratch[y*w+x]) {
3242                 if (ui->dragging && ui->srcx == x*2+1 && ui->srcy == y*2+1) {
3243                     /* don't do it */
3244                 } else if (sp->doty != y*2+1 || sp->dotx != x*2+1) {
3245                     flags |= DRAW_ARROW;
3246                     ddy = sp->doty - (y*2+1);
3247                     ddx = sp->dotx - (x*2+1);
3248                 }
3249             }
3250
3251             /*
3252              * Now go through the nine possible places we could
3253              * have dots.
3254              */
3255             for (dy = 0; dy < 3; dy++)
3256                 for (dx = 0; dx < 3; dx++) {
3257                     sp = &SPACE(state, x*2+dx, y*2+dy);
3258                     if (sp->flags & F_DOT) {
3259                         unsigned long dotval = (sp->flags & F_DOT_BLACK ?
3260                                                 DOT_BLACK : DOT_WHITE);
3261                         flags |= dotval << (DOT_SHIFT_C +
3262                                             DOT_SHIFT_M*(dy*3+dx));
3263                     }
3264                 }
3265
3266             /*
3267              * Now work out if we have to draw a cursor for this square;
3268              * cursors-on-lines are taken care of below.
3269              */
3270             if (ui->cur_visible &&
3271                 ui->cur_x == x*2+1 && ui->cur_y == y*2+1 &&
3272                 !(SPACE(state, x*2+1, y*2+1).flags & F_DOT))
3273                 flags |= DRAW_CURSOR;
3274
3275             /*
3276              * Now we have everything we're going to need. Draw the
3277              * square.
3278              */
3279             if (ds->grid[y*w+x] != flags ||
3280                 ds->dx[y*w+x] != ddx ||
3281                 ds->dy[y*w+x] != ddy) {
3282                 draw_square(dr, ds, x, y, flags, ddx, ddy);
3283                 ds->grid[y*w+x] = flags;
3284                 ds->dx[y*w+x] = ddx;
3285                 ds->dy[y*w+x] = ddy;
3286             }
3287         }
3288
3289     /*
3290      * Draw a cursor. This secondary blitter is much less invasive than trying
3291      * to fix up all of the rest of the code with sufficient flags to be able to
3292      * display this sensibly.
3293      */
3294     if (ui->cur_visible) {
3295         space *sp = &SPACE(state, ui->cur_x, ui->cur_y);
3296         ds->cur_visible = TRUE;
3297         ds->cx = SCOORD(ui->cur_x) - CURSOR_SIZE;
3298         ds->cy = SCOORD(ui->cur_y) - CURSOR_SIZE;
3299         blitter_save(dr, ds->cur_bl, ds->cx, ds->cy);
3300         if (sp->flags & F_DOT) {
3301             /* draw a red dot (over the top of whatever would be there already) */
3302             draw_circle(dr, SCOORD(ui->cur_x), SCOORD(ui->cur_y), DOT_SIZE,
3303                         COL_CURSOR, COL_BLACKDOT);
3304         } else if (sp->type != s_tile) {
3305             /* draw an edge/vertex square; tile cursors are dealt with above. */
3306             int dx = (ui->cur_x % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3307             int dy = (ui->cur_y % 2) ? CURSOR_SIZE : CURSOR_SIZE/3;
3308             int x1 = SCOORD(ui->cur_x)-dx, y1 = SCOORD(ui->cur_y)-dy;
3309             int xs = dx*2+1, ys = dy*2+1;
3310
3311             draw_rect(dr, x1, y1, xs, ys, COL_CURSOR);
3312         }
3313         draw_update(dr, ds->cx, ds->cy, CURSOR_SIZE*2+1, CURSOR_SIZE*2+1);
3314     }
3315
3316     if (ui->dragging) {
3317         ds->dragging = TRUE;
3318         ds->dragx = ui->dx - TILE_SIZE/2;
3319         ds->dragy = ui->dy - TILE_SIZE/2;
3320         blitter_save(dr, ds->bl, ds->dragx, ds->dragy);
3321         draw_arrow(dr, ds, ui->dx, ui->dy,
3322                    SCOORD(ui->dotx) - ui->dx,
3323                    SCOORD(ui->doty) - ui->dy, COL_ARROW);
3324     }
3325 #ifdef EDITOR
3326     {
3327         char buf[256];
3328         if (state->cdiff != -1)
3329             sprintf(buf, "Puzzle is %s.", galaxies_diffnames[state->cdiff]);
3330         else
3331             buf[0] = '\0';
3332         status_bar(dr, buf);
3333     }
3334 #endif
3335 }
3336
3337 static float game_anim_length(const game_state *oldstate,
3338                               const game_state *newstate, int dir, game_ui *ui)
3339 {
3340     return 0.0F;
3341 }
3342
3343 static float game_flash_length(const game_state *oldstate,
3344                                const game_state *newstate, int dir, game_ui *ui)
3345 {
3346     if ((!oldstate->completed && newstate->completed) &&
3347         !(newstate->used_solve))
3348         return 3 * FLASH_TIME;
3349     else
3350         return 0.0F;
3351 }
3352
3353 static int game_status(const game_state *state)
3354 {
3355     return state->completed ? +1 : 0;
3356 }
3357
3358 static int game_timing_state(const game_state *state, game_ui *ui)
3359 {
3360     return TRUE;
3361 }
3362
3363 #ifndef EDITOR
3364 static void game_print_size(const game_params *params, float *x, float *y)
3365 {
3366    int pw, ph;
3367
3368    /*
3369     * 8mm squares by default. (There isn't all that much detail
3370     * that needs to go in each square.)
3371     */
3372    game_compute_size(params, 800, &pw, &ph);
3373    *x = pw / 100.0F;
3374    *y = ph / 100.0F;
3375 }
3376
3377 static void game_print(drawing *dr, const game_state *state, int sz)
3378 {
3379     int w = state->w, h = state->h;
3380     int white, black, blackish;
3381     int x, y, i, j;
3382     int *colours, *dsf;
3383     int *coords = NULL;
3384     int ncoords = 0, coordsize = 0;
3385
3386     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3387     game_drawstate ads, *ds = &ads;
3388     ds->tilesize = sz;
3389
3390     white = print_mono_colour(dr, 1);
3391     black = print_mono_colour(dr, 0);
3392     blackish = print_hatched_colour(dr, HATCH_X);
3393
3394     /*
3395      * Get the completion information.
3396      */
3397     dsf = snewn(w * h, int);
3398     colours = snewn(w * h, int);
3399     check_complete(state, dsf, colours);
3400
3401     /*
3402      * Draw the grid.
3403      */
3404     print_line_width(dr, TILE_SIZE / 64);
3405     for (x = 1; x < w; x++)
3406         draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
3407     for (y = 1; y < h; y++)
3408         draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
3409
3410     /*
3411      * Shade the completed regions. Just in case any particular
3412      * printing platform deals badly with adjacent
3413      * similarly-hatched regions, we'll fill each one as a single
3414      * polygon.
3415      */
3416     for (i = 0; i < w*h; i++) {
3417         j = dsf_canonify(dsf, i);
3418         if (colours[j] != 0) {
3419             int dx, dy, t;
3420
3421             /*
3422              * This is the first square we've run into belonging to
3423              * this polyomino, which means an edge of the polyomino
3424              * is certain to be to our left. (After we finish
3425              * tracing round it, we'll set the colours[] entry to
3426              * zero to prevent accidentally doing it again.)
3427              */
3428
3429             x = i % w;
3430             y = i / w;
3431             dx = -1;
3432             dy = 0;
3433             ncoords = 0;
3434             while (1) {
3435                 /*
3436                  * We are currently sitting on square (x,y), which
3437                  * we know to be in our polyomino, and we also know
3438                  * that (x+dx,y+dy) is not. The way I visualise
3439                  * this is that we're standing to the right of a
3440                  * boundary line, stretching our left arm out to
3441                  * point to the exterior square on the far side.
3442                  */
3443
3444                 /*
3445                  * First, check if we've gone round the entire
3446                  * polyomino.
3447                  */
3448                 if (ncoords > 0 &&
3449                     (x == i%w && y == i/w && dx == -1 && dy == 0))
3450                     break;
3451
3452                 /*
3453                  * Add to our coordinate list the coordinate
3454                  * backwards and to the left of where we are.
3455                  */
3456                 if (ncoords + 2 > coordsize) {
3457                     coordsize = (ncoords * 3 / 2) + 64;
3458                     coords = sresize(coords, coordsize, int);
3459                 }
3460                 coords[ncoords++] = COORD((2*x+1 + dx + dy) / 2);
3461                 coords[ncoords++] = COORD((2*y+1 + dy - dx) / 2);
3462
3463                 /*
3464                  * Follow the edge round. If the square directly in
3465                  * front of us is not part of the polyomino, we
3466                  * turn right; if it is and so is the square in
3467                  * front of (x+dx,y+dy), we turn left; otherwise we
3468                  * go straight on.
3469                  */
3470                 if (x-dy < 0 || x-dy >= w || y+dx < 0 || y+dx >= h ||
3471                     dsf_canonify(dsf, (y+dx)*w+(x-dy)) != j) {
3472                     /* Turn right. */
3473                     t = dx;
3474                     dx = -dy;
3475                     dy = t;
3476                 } else if (x+dx-dy >= 0 && x+dx-dy < w &&
3477                            y+dy+dx >= 0 && y+dy+dx < h &&
3478                            dsf_canonify(dsf, (y+dy+dx)*w+(x+dx-dy)) == j) {
3479                     /* Turn left. */
3480                     x += dx;
3481                     y += dy;
3482                     t = dx;
3483                     dx = dy;
3484                     dy = -t;
3485                     x -= dx;
3486                     y -= dy;
3487                 } else {
3488                     /* Straight on. */
3489                     x -= dy;
3490                     y += dx;
3491                 }
3492             }
3493
3494             /*
3495              * Now we have our polygon complete, so fill it.
3496              */
3497             draw_polygon(dr, coords, ncoords/2,
3498                          colours[j] == 2 ? blackish : -1, black);
3499
3500             /*
3501              * And mark this polyomino as done.
3502              */
3503             colours[j] = 0;
3504         }
3505     }
3506
3507     /*
3508      * Draw the edges.
3509      */
3510     for (y = 0; y <= h; y++)
3511         for (x = 0; x <= w; x++) {
3512             if (x < w && SPACE(state, x*2+1, y*2).flags & F_EDGE_SET)
3513                 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3514                           EDGE_THICKNESS * 2 + TILE_SIZE, EDGE_THICKNESS * 2,
3515                           black);
3516             if (y < h && SPACE(state, x*2, y*2+1).flags & F_EDGE_SET)
3517                 draw_rect(dr, COORD(x)-EDGE_THICKNESS, COORD(y)-EDGE_THICKNESS,
3518                           EDGE_THICKNESS * 2, EDGE_THICKNESS * 2 + TILE_SIZE,
3519                           black);
3520         }
3521
3522     /*
3523      * Draw the dots.
3524      */
3525     for (y = 0; y <= 2*h; y++)
3526         for (x = 0; x <= 2*w; x++)
3527             if (SPACE(state, x, y).flags & F_DOT) {
3528                 draw_circle(dr, (int)COORD(x/2.0), (int)COORD(y/2.0), DOT_SIZE,
3529                             (SPACE(state, x, y).flags & F_DOT_BLACK ?
3530                              black : white), black);
3531             }
3532
3533     sfree(dsf);
3534     sfree(colours);
3535     sfree(coords);
3536 }
3537 #endif
3538
3539 #ifdef COMBINED
3540 #define thegame galaxies
3541 #endif
3542
3543 const struct game thegame = {
3544     "Galaxies", "games.galaxies", "galaxies",
3545     default_params,
3546     game_fetch_preset,
3547     decode_params,
3548     encode_params,
3549     free_params,
3550     dup_params,
3551     TRUE, game_configure, custom_params,
3552     validate_params,
3553     new_game_desc,
3554     validate_desc,
3555     new_game,
3556     dup_game,
3557     free_game,
3558 #ifdef EDITOR
3559     FALSE, NULL,
3560 #else
3561     TRUE, solve_game,
3562 #endif
3563     TRUE, game_can_format_as_text_now, game_text_format,
3564     new_ui,
3565     free_ui,
3566     encode_ui,
3567     decode_ui,
3568     game_changed_state,
3569     interpret_move,
3570     execute_move,
3571     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3572     game_colours,
3573     game_new_drawstate,
3574     game_free_drawstate,
3575     game_redraw,
3576     game_anim_length,
3577     game_flash_length,
3578     game_status,
3579 #ifdef EDITOR
3580     FALSE, FALSE, NULL, NULL,
3581     TRUE,                              /* wants_statusbar */
3582 #else
3583     TRUE, FALSE, game_print_size, game_print,
3584     FALSE,                             /* wants_statusbar */
3585 #endif
3586     FALSE, game_timing_state,
3587     REQUIRE_RBUTTON,                   /* flags */
3588 };
3589
3590 #ifdef STANDALONE_SOLVER
3591
3592 const char *quis;
3593
3594 #include <time.h>
3595
3596 static void usage_exit(const char *msg)
3597 {
3598     if (msg)
3599         fprintf(stderr, "%s: %s\n", quis, msg);
3600     fprintf(stderr, "Usage: %s [--seed SEED] --soak <params> | [game_id [game_id ...]]\n", quis);
3601     exit(1);
3602 }
3603
3604 static void dump_state(game_state *state)
3605 {
3606     char *temp = game_text_format(state);
3607     printf("%s\n", temp);
3608     sfree(temp);
3609 }
3610
3611 static int gen(game_params *p, random_state *rs, int debug)
3612 {
3613     char *desc;
3614     int diff;
3615     game_state *state;
3616
3617 #ifndef DEBUGGING
3618     solver_show_working = debug;
3619 #endif
3620     printf("Generating a %dx%d %s puzzle.\n",
3621            p->w, p->h, galaxies_diffnames[p->diff]);
3622
3623     desc = new_game_desc(p, rs, NULL, 0);
3624     state = new_game(NULL, p, desc);
3625     dump_state(state);
3626
3627     diff = solver_state(state, DIFF_UNREASONABLE);
3628     printf("Generated %s game %dx%d:%s\n",
3629            galaxies_diffnames[diff], p->w, p->h, desc);
3630     dump_state(state);
3631
3632     free_game(state);
3633     sfree(desc);
3634
3635     return diff;
3636 }
3637
3638 static void soak(game_params *p, random_state *rs)
3639 {
3640     time_t tt_start, tt_now, tt_last;
3641     char *desc;
3642     game_state *st;
3643     int diff, n = 0, i, diffs[DIFF_MAX], ndots = 0, nspaces = 0;
3644
3645 #ifndef DEBUGGING
3646     solver_show_working = 0;
3647 #endif
3648     tt_start = tt_now = time(NULL);
3649     for (i = 0; i < DIFF_MAX; i++) diffs[i] = 0;
3650     maxtries = 1;
3651
3652     printf("Soak-generating a %dx%d grid, max. diff %s.\n",
3653            p->w, p->h, galaxies_diffnames[p->diff]);
3654     printf("   [");
3655     for (i = 0; i < DIFF_MAX; i++)
3656         printf("%s%s", (i == 0) ? "" : ", ", galaxies_diffnames[i]);
3657     printf("]\n");
3658
3659     while (1) {
3660         desc = new_game_desc(p, rs, NULL, 0);
3661         st = new_game(NULL, p, desc);
3662         diff = solver_state(st, p->diff);
3663         nspaces += st->w*st->h;
3664         for (i = 0; i < st->sx*st->sy; i++)
3665             if (st->grid[i].flags & F_DOT) ndots++;
3666         free_game(st);
3667         sfree(desc);
3668
3669         diffs[diff]++;
3670         n++;
3671         tt_last = time(NULL);
3672         if (tt_last > tt_now) {
3673             tt_now = tt_last;
3674             printf("%d total, %3.1f/s, [",
3675                    n, (double)n / ((double)tt_now - tt_start));
3676             for (i = 0; i < DIFF_MAX; i++)
3677                 printf("%s%.1f%%", (i == 0) ? "" : ", ",
3678                        100.0 * ((double)diffs[i] / (double)n));
3679             printf("], %.1f%% dots\n",
3680                    100.0 * ((double)ndots / (double)nspaces));
3681         }
3682     }
3683 }
3684
3685 int main(int argc, char **argv)
3686 {
3687     game_params *p;
3688     char *id = NULL, *desc, *err;
3689     game_state *s;
3690     int diff, do_soak = 0, verbose = 0;
3691     random_state *rs;
3692     time_t seed = time(NULL);
3693
3694     quis = argv[0];
3695     while (--argc > 0) {
3696         char *p = *++argv;
3697         if (!strcmp(p, "-v")) {
3698             verbose = 1;
3699         } else if (!strcmp(p, "--seed")) {
3700             if (argc == 0) usage_exit("--seed needs an argument");
3701             seed = (time_t)atoi(*++argv);
3702             argc--;
3703         } else if (!strcmp(p, "--soak")) {
3704             do_soak = 1;
3705         } else if (*p == '-') {
3706             usage_exit("unrecognised option");
3707         } else {
3708             id = p;
3709         }
3710     }
3711
3712     maxtries = 50;
3713
3714     p = default_params();
3715     rs = random_new((void*)&seed, sizeof(time_t));
3716
3717     if (do_soak) {
3718         if (!id) usage_exit("need one argument for --soak");
3719         decode_params(p, *argv);
3720         soak(p, rs);
3721         return 0;
3722     }
3723
3724     if (!id) {
3725         while (1) {
3726             p->w = random_upto(rs, 15) + 3;
3727             p->h = random_upto(rs, 15) + 3;
3728             p->diff = random_upto(rs, DIFF_UNREASONABLE);
3729             diff = gen(p, rs, 0);
3730         }
3731         return 0;
3732     }
3733
3734     desc = strchr(id, ':');
3735     if (!desc) {
3736         decode_params(p, id);
3737         gen(p, rs, verbose);
3738     } else {
3739 #ifndef DEBUGGING
3740         solver_show_working = 1;
3741 #endif
3742         *desc++ = '\0';
3743         decode_params(p, id);
3744         err = validate_desc(p, desc);
3745         if (err) {
3746             fprintf(stderr, "%s: %s\n", argv[0], err);
3747             exit(1);
3748         }
3749         s = new_game(NULL, p, desc);
3750         diff = solver_state(s, DIFF_UNREASONABLE);
3751         dump_state(s);
3752         printf("Puzzle is %s.\n", galaxies_diffnames[diff]);
3753         free_game(s);
3754     }
3755
3756     free_params(p);
3757
3758     return 0;
3759 }
3760
3761 #endif
3762
3763 #ifdef STANDALONE_PICTURE_GENERATOR
3764
3765 /*
3766  * Main program for the standalone picture generator. To use it,
3767  * simply provide it with an XBM-format bitmap file (note XBM, not
3768  * XPM) on standard input, and it will output a game ID in return.
3769  * For example:
3770  *
3771  *   $ ./galaxiespicture < badly-drawn-cat.xbm
3772  *   11x11:eloMBLzFeEzLNMWifhaWYdDbixCymBbBMLoDdewGg
3773  *
3774  * If you want a puzzle with a non-standard difficulty level, pass
3775  * a partial parameters string as a command-line argument (e.g.
3776  * `./galaxiespicture du < foo.xbm', where `du' is the same suffix
3777  * which if it appeared in a random-seed game ID would set the
3778  * difficulty level to Unreasonable). However, be aware that if the
3779  * generator fails to produce an adequately difficult puzzle too
3780  * many times then it will give up and return an easier one (just
3781  * as it does during normal GUI play). To be sure you really have
3782  * the difficulty you asked for, use galaxiessolver to
3783  * double-check.
3784  * 
3785  * (Perhaps I ought to include an option to make this standalone
3786  * generator carry on looping until it really does get the right
3787  * difficulty. Hmmm.)
3788  */
3789
3790 #include <time.h>
3791
3792 int main(int argc, char **argv)
3793 {
3794     game_params *par;
3795     char *params, *desc;
3796     random_state *rs;
3797     time_t seed = time(NULL);
3798     char buf[4096];
3799     int i;
3800     int x, y;
3801
3802     par = default_params();
3803     if (argc > 1)
3804         decode_params(par, argv[1]);   /* get difficulty */
3805     par->w = par->h = -1;
3806
3807     /*
3808      * Now read an XBM file from standard input. This is simple and
3809      * hacky and will do very little error detection, so don't feed
3810      * it bogus data.
3811      */
3812     picture = NULL;
3813     x = y = 0;
3814     while (fgets(buf, sizeof(buf), stdin)) {
3815         buf[strcspn(buf, "\r\n")] = '\0';
3816         if (!strncmp(buf, "#define", 7)) {
3817             /*
3818              * Lines starting `#define' give the width and height.
3819              */
3820             char *num = buf + strlen(buf);
3821             char *symend;
3822
3823             while (num > buf && isdigit((unsigned char)num[-1]))
3824                 num--;
3825             symend = num;
3826             while (symend > buf && isspace((unsigned char)symend[-1]))
3827                 symend--;
3828
3829             if (symend-5 >= buf && !strncmp(symend-5, "width", 5))
3830                 par->w = atoi(num);
3831             else if (symend-6 >= buf && !strncmp(symend-6, "height", 6))
3832                 par->h = atoi(num);
3833         } else {
3834             /*
3835              * Otherwise, break the string up into words and take
3836              * any word of the form `0x' plus hex digits to be a
3837              * byte.
3838              */
3839             char *p, *wordstart;
3840
3841             if (!picture) {
3842                 if (par->w < 0 || par->h < 0) {
3843                     printf("failed to read width and height\n");
3844                     return 1;
3845                 }
3846                 picture = snewn(par->w * par->h, int);
3847                 for (i = 0; i < par->w * par->h; i++)
3848                     picture[i] = -1;
3849             }
3850
3851             p = buf;
3852             while (*p) {
3853                 while (*p && (*p == ',' || isspace((unsigned char)*p)))
3854                     p++;
3855                 wordstart = p;
3856                 while (*p && !(*p == ',' || *p == '}' ||
3857                                isspace((unsigned char)*p)))
3858                     p++;
3859                 if (*p)
3860                     *p++ = '\0';
3861
3862                 if (wordstart[0] == '0' &&
3863                     (wordstart[1] == 'x' || wordstart[1] == 'X') &&
3864                     !wordstart[2 + strspn(wordstart+2,
3865                                           "0123456789abcdefABCDEF")]) {
3866                     unsigned long byte = strtoul(wordstart+2, NULL, 16);
3867                     for (i = 0; i < 8; i++) {
3868                         int bit = (byte >> i) & 1;
3869                         if (y < par->h && x < par->w)
3870                             picture[y * par->w + x] = bit;
3871                         x++;
3872                     }
3873
3874                     if (x >= par->w) {
3875                         x = 0;
3876                         y++;
3877                     }
3878                 }
3879             }
3880         }
3881     }
3882
3883     for (i = 0; i < par->w * par->h; i++)
3884         if (picture[i] < 0) {
3885             fprintf(stderr, "failed to read enough bitmap data\n");
3886             return 1;
3887         }
3888
3889     rs = random_new((void*)&seed, sizeof(time_t));
3890
3891     desc = new_game_desc(par, rs, NULL, FALSE);
3892     params = encode_params(par, FALSE);
3893     printf("%s:%s\n", params, desc);
3894
3895     sfree(desc);
3896     sfree(params);
3897     free_params(par);
3898     random_free(rs);
3899
3900     return 0;
3901 }
3902
3903 #endif
3904
3905 /* vim: set shiftwidth=4 tabstop=8: */