Debian requires -lm, where Red Hat didn't.
[sgt/puzzles] / map.c
diff --git a/map.c b/map.c
index 0f5920c..2727165 100644 (file)
--- a/map.c
+++ b/map.c
@@ -6,9 +6,9 @@
  * TODO:
  * 
  *  - clue marking
- *  - more solver brains?
  *  - better four-colouring algorithm?
- *  - pencil marks?
+ *  - can we make the pencil marks look nicer?
+ *  - ability to drag a set of pencil marks?
  */
 
 #include <stdio.h>
 #include "puzzles.h"
 
 /*
+ * In standalone solver mode, `verbose' is a variable which can be
+ * set by command-line option; in debugging mode it's simply always
+ * true.
+ */
+#if defined STANDALONE_SOLVER
+#define SOLVER_DIAGNOSTICS
+int verbose = FALSE;
+#elif defined SOLVER_DIAGNOSTICS
+#define verbose TRUE
+#endif
+
+/*
  * I don't seriously anticipate wanting to change the number of
  * colours used in this game, but it doesn't cost much to use a
  * #define just in case :-)
@@ -43,6 +55,7 @@ static float flash_length;
 #define DIFFLIST(A) \
     A(EASY,Easy,e) \
     A(NORMAL,Normal,n) \
+    A(HARD,Hard,h) \
     A(RECURSE,Unreasonable,u)
 #define ENUM(upper,title,lower) DIFF_ ## upper,
 #define TITLE(upper,title,lower) #title,
@@ -74,13 +87,14 @@ struct map {
     int n;
     int ngraph;
     int *immutable;
-    int *edgex, *edgey;                       /* positions of a point on each edge */
+    int *edgex, *edgey;                       /* position of a point on each edge */
+    int *regionx, *regiony;            /* position of a point in each region */
 };
 
 struct game_state {
     game_params p;
     struct map *map;
-    int *colouring;
+    int *colouring, *pencil;
     int completed, cheated;
 };
 
@@ -99,7 +113,10 @@ static game_params *default_params(void)
 static const struct game_params map_presets[] = {
     {20, 15, 30, DIFF_EASY},
     {20, 15, 30, DIFF_NORMAL},
+    {20, 15, 30, DIFF_HARD},
+    {20, 15, 30, DIFF_RECURSE},
     {30, 25, 75, DIFF_NORMAL},
+    {30, 25, 75, DIFF_HARD},
 };
 
 static int game_fetch_preset(int i, char **name, game_params **params)
@@ -787,9 +804,17 @@ static void fourcolour(int *graph, int n, int ngraph, int *colouring,
 
 struct solver_scratch {
     unsigned char *possible;          /* bitmap of colours for each region */
+
     int *graph;
     int n;
     int ngraph;
+
+    int *bfsqueue;
+    int *bfscolour;
+#ifdef SOLVER_DIAGNOSTICS
+    int *bfsprev;
+#endif
+
     int depth;
 };
 
@@ -803,6 +828,11 @@ static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
     sc->ngraph = ngraph;
     sc->possible = snewn(n, unsigned char);
     sc->depth = 0;
+    sc->bfsqueue = snewn(n, int);
+    sc->bfscolour = snewn(n, int);
+#ifdef SOLVER_DIAGNOSTICS
+    sc->bfsprev = snewn(n, int);
+#endif
 
     return sc;
 }
@@ -810,33 +840,91 @@ static struct solver_scratch *new_scratch(int *graph, int n, int ngraph)
 static void free_scratch(struct solver_scratch *sc)
 {
     sfree(sc->possible);
+    sfree(sc->bfsqueue);
+    sfree(sc->bfscolour);
+#ifdef SOLVER_DIAGNOSTICS
+    sfree(sc->bfsprev);
+#endif
     sfree(sc);
 }
 
+/*
+ * Count the bits in a word. Only needs to cope with FOUR bits.
+ */
+static int bitcount(int word)
+{
+    assert(FOUR <= 4);                 /* or this needs changing */
+    word = ((word & 0xA) >> 1) + (word & 0x5);
+    word = ((word & 0xC) >> 2) + (word & 0x3);
+    return word;
+}
+
+#ifdef SOLVER_DIAGNOSTICS
+static const char colnames[FOUR] = { 'R', 'Y', 'G', 'B' };
+#endif
+
 static int place_colour(struct solver_scratch *sc,
-                       int *colouring, int index, int colour)
+                       int *colouring, int index, int colour
+#ifdef SOLVER_DIAGNOSTICS
+                        , char *verb
+#endif
+                        )
 {
     int *graph = sc->graph, n = sc->n, ngraph = sc->ngraph;
     int j, k;
 
-    if (!(sc->possible[index] & (1 << colour)))
+    if (!(sc->possible[index] & (1 << colour))) {
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose)
+            printf("%*scannot place %c in region %d\n", 2*sc->depth, "",
+                   colnames[colour], index);
+#endif
        return FALSE;                  /* can't do it */
+    }
 
     sc->possible[index] = 1 << colour;
     colouring[index] = colour;
 
+#ifdef SOLVER_DIAGNOSTICS
+    if (verbose)
+       printf("%*s%s %c in region %d\n", 2*sc->depth, "",
+               verb, colnames[colour], index);
+#endif
+
     /*
      * Rule out this colour from all the region's neighbours.
      */
     for (j = graph_vertex_start(graph, n, ngraph, index);
         j < ngraph && graph[j] < n*(index+1); j++) {
        k = graph[j] - index*n;
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose && (sc->possible[k] & (1 << colour)))
+            printf("%*s  ruling out %c in region %d\n", 2*sc->depth, "",
+                   colnames[colour], k);
+#endif
        sc->possible[k] &= ~(1 << colour);
     }
 
     return TRUE;
 }
 
+#ifdef SOLVER_DIAGNOSTICS
+static char *colourset(char *buf, int set)
+{
+    int i;
+    char *p = buf;
+    char *sep = "";
+
+    for (i = 0; i < FOUR; i++)
+        if (set & (1 << i)) {
+            p += sprintf(p, "%s%c", sep, colnames[i]);
+            sep = ",";
+        }
+
+    return buf;
+}
+#endif
+
 /*
  * Returns 0 for impossible, 1 for success, 2 for failure to
  * converge (i.e. puzzle is either ambiguous or just too
@@ -848,20 +936,32 @@ static int map_solver(struct solver_scratch *sc,
 {
     int i;
 
-    /*
-     * Initialise scratch space.
-     */
-    for (i = 0; i < n; i++)
-       sc->possible[i] = (1 << FOUR) - 1;
+    if (sc->depth == 0) {
+        /*
+         * Initialise scratch space.
+         */
+        for (i = 0; i < n; i++)
+            sc->possible[i] = (1 << FOUR) - 1;
 
-    /*
-     * Place clues.
-     */
-    for (i = 0; i < n; i++)
-       if (colouring[i] >= 0) {
-           if (!place_colour(sc, colouring, i, colouring[i]))
-               return 0;              /* the clues aren't even consistent! */
-       }
+        /*
+         * Place clues.
+         */
+        for (i = 0; i < n; i++)
+            if (colouring[i] >= 0) {
+                if (!place_colour(sc, colouring, i, colouring[i]
+#ifdef SOLVER_DIAGNOSTICS
+                                  , "initial clue:"
+#endif
+                                  )) {
+#ifdef SOLVER_DIAGNOSTICS
+                    if (verbose)
+                        printf("%*sinitial clue set is inconsistent\n",
+                               2*sc->depth, "");
+#endif
+                    return 0;         /* the clues aren't even consistent! */
+                }
+            }
+    }
 
     /*
      * Now repeatedly loop until we find nothing further to do.
@@ -879,17 +979,35 @@ static int map_solver(struct solver_scratch *sc,
        for (i = 0; i < n; i++) if (colouring[i] < 0) {
            int p = sc->possible[i];
 
-           if (p == 0)
+           if (p == 0) {
+#ifdef SOLVER_DIAGNOSTICS
+                if (verbose)
+                    printf("%*sregion %d has no possible colours left\n",
+                           2*sc->depth, "", i);
+#endif
                return 0;              /* puzzle is inconsistent */
+            }
 
            if ((p & (p-1)) == 0) {    /* p is a power of two */
-               int c;
+               int c, ret;
                for (c = 0; c < FOUR; c++)
                    if (p == (1 << c))
                        break;
                assert(c < FOUR);
-               if (!place_colour(sc, colouring, i, c))
-                   return 0;          /* found puzzle to be inconsistent */
+               ret = place_colour(sc, colouring, i, c
+#ifdef SOLVER_DIAGNOSTICS
+                                   , "placing"
+#endif
+                                   );
+                /*
+                 * place_colour() can only fail if colour c was not
+                 * even a _possibility_ for region i, and we're
+                 * pretty sure it was because we checked before
+                 * calling place_colour(). So we can safely assert
+                 * here rather than having to return a nice
+                 * friendly error code.
+                 */
+                assert(ret);
                done_something = TRUE;
            }
        }
@@ -914,6 +1032,9 @@ static int map_solver(struct solver_scratch *sc,
         for (i = 0; i < ngraph; i++) {
             int j1 = graph[i] / n, j2 = graph[i] % n;
             int j, k, v, v2;
+#ifdef SOLVER_DIAGNOSTICS
+            int started = FALSE;
+#endif
 
             if (j1 > j2)
                 continue;              /* done it already, other way round */
@@ -949,12 +1070,168 @@ static int map_solver(struct solver_scratch *sc,
                 k = graph[j] - j1*n;
                 if (graph_adjacent(graph, n, ngraph, k, j2) &&
                     (sc->possible[k] & v)) {
+#ifdef SOLVER_DIAGNOSTICS
+                    if (verbose) {
+                        char buf[80];
+                        if (!started)
+                            printf("%*sadjacent regions %d,%d share colours"
+                                   " %s\n", 2*sc->depth, "", j1, j2,
+                                   colourset(buf, v));
+                        started = TRUE;
+                        printf("%*s  ruling out %s in region %d\n",2*sc->depth,
+                               "", colourset(buf, sc->possible[k] & v), k);
+                    }
+#endif
                     sc->possible[k] &= ~v;
                     done_something = TRUE;
                 }
             }
         }
 
+        if (done_something)
+            continue;
+
+        if (difficulty < DIFF_HARD)
+            break;                     /* can't do anything harder */
+
+        /*
+         * Right; now we get creative. Now we're going to look for
+         * `forcing chains'. A forcing chain is a path through the
+         * graph with the following properties:
+         * 
+         *  (a) Each vertex on the path has precisely two possible
+         *      colours.
+         * 
+         *  (b) Each pair of vertices which are adjacent on the
+         *      path share at least one possible colour in common.
+         * 
+         *  (c) Each vertex in the middle of the path shares _both_
+         *      of its colours with at least one of its neighbours
+         *      (not the same one with both neighbours).
+         * 
+         * These together imply that at least one of the possible
+         * colour choices at one end of the path forces _all_ the
+         * rest of the colours along the path. In order to make
+         * real use of this, we need further properties:
+         * 
+         *  (c) Ruling out some colour C from the vertex at one end
+         *      of the path forces the vertex at the other end to
+         *      take colour C.
+         * 
+         *  (d) The two end vertices are mutually adjacent to some
+         *      third vertex.
+         * 
+         *  (e) That third vertex currently has C as a possibility.
+         * 
+         * If we can find all of that lot, we can deduce that at
+         * least one of the two ends of the forcing chain has
+         * colour C, and that therefore the mutually adjacent third
+         * vertex does not.
+         * 
+         * To find forcing chains, we're going to start a bfs at
+         * each suitable vertex of the graph, once for each of its
+         * two possible colours.
+         */
+        for (i = 0; i < n; i++) {
+            int c;
+
+            if (colouring[i] >= 0 || bitcount(sc->possible[i]) != 2)
+                continue;
+
+            for (c = 0; c < FOUR; c++)
+                if (sc->possible[i] & (1 << c)) {
+                    int j, k, gi, origc, currc, head, tail;
+                    /*
+                     * Try a bfs from this vertex, ruling out
+                     * colour c.
+                     * 
+                     * Within this loop, we work in colour bitmaps
+                     * rather than actual colours, because
+                     * converting back and forth is a needless
+                     * computational expense.
+                     */
+
+                    origc = 1 << c;
+
+                    for (j = 0; j < n; j++) {
+                        sc->bfscolour[j] = -1;
+#ifdef SOLVER_DIAGNOSTICS
+                        sc->bfsprev[j] = -1;
+#endif
+                    }
+                    head = tail = 0;
+                    sc->bfsqueue[tail++] = i;
+                    sc->bfscolour[i] = sc->possible[i] &~ origc;
+
+                    while (head < tail) {
+                        j = sc->bfsqueue[head++];
+                        currc = sc->bfscolour[j];
+
+                        /*
+                         * Try neighbours of j.
+                         */
+                        for (gi = graph_vertex_start(graph, n, ngraph, j);
+                             gi < ngraph && graph[gi] < n*(j+1); gi++) {
+                            k = graph[gi] - j*n;
+
+                            /*
+                             * To continue with the bfs in vertex
+                             * k, we need k to be
+                             *  (a) not already visited
+                             *  (b) have two possible colours
+                             *  (c) those colours include currc.
+                             */
+
+                            if (sc->bfscolour[k] < 0 &&
+                                colouring[k] < 0 &&
+                                bitcount(sc->possible[k]) == 2 &&
+                                (sc->possible[k] & currc)) {
+                                sc->bfsqueue[tail++] = k;
+                                sc->bfscolour[k] =
+                                    sc->possible[k] &~ currc;
+#ifdef SOLVER_DIAGNOSTICS
+                                sc->bfsprev[k] = j;
+#endif
+                            }
+
+                            /*
+                             * One other possibility is that k
+                             * might be the region in which we can
+                             * make a real deduction: if it's
+                             * adjacent to i, contains currc as a
+                             * possibility, and currc is equal to
+                             * the original colour we ruled out.
+                             */
+                            if (currc == origc &&
+                                graph_adjacent(graph, n, ngraph, k, i) &&
+                                (sc->possible[k] & currc)) {
+#ifdef SOLVER_DIAGNOSTICS
+                                if (verbose) {
+                                    char buf[80], *sep = "";
+                                    int r;
+
+                                    printf("%*sforcing chain, colour %s, ",
+                                           2*sc->depth, "",
+                                           colourset(buf, origc));
+                                    for (r = j; r != -1; r = sc->bfsprev[r]) {
+                                        printf("%s%d", sep, r);
+                                        sep = "-";
+                                    }
+                                    printf("\n%*s  ruling out %s in region"
+                                           " %d\n", 2*sc->depth, "",
+                                           colourset(buf, origc), k);
+                                }
+#endif
+                                sc->possible[k] &= ~origc;
+                                done_something = TRUE;
+                            }
+                        }
+                    }
+
+                    assert(tail <= n);
+                }
+        }
+
        if (!done_something)
            break;
     }
@@ -965,14 +1242,25 @@ static int map_solver(struct solver_scratch *sc,
     for (i = 0; i < n; i++)
        if (colouring[i] < 0)
             break;
-    if (i == n)
+    if (i == n) {
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose)
+            printf("%*sone solution found\n", 2*sc->depth, "");
+#endif
         return 1;                      /* success! */
+    }
 
     /*
      * If recursion is not permissible, we now give up.
      */
-    if (difficulty < DIFF_RECURSE)
+    if (difficulty < DIFF_RECURSE) {
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose)
+            printf("%*sunable to proceed further without recursion\n",
+                   2*sc->depth, "");
+#endif
         return 2;                      /* unable to complete */
+    }
 
     /*
      * Now we've got to do something recursive. So first hunt for a
@@ -1006,6 +1294,11 @@ static int map_solver(struct solver_scratch *sc,
 
         assert(best >= 0);             /* or we'd be solved already */
 
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose)
+            printf("%*srecursing on region %d\n", 2*sc->depth, "", best);
+#endif
+
         /*
          * Now iterate over the possible colours for this region.
          */
@@ -1021,11 +1314,27 @@ static int map_solver(struct solver_scratch *sc,
             if (!(sc->possible[best] & (1 << i)))
                 continue;
 
+            memcpy(rsc->possible, sc->possible, n);
             memcpy(subcolouring, origcolouring, n * sizeof(int));
-            subcolouring[best] = i;
+
+            place_colour(rsc, subcolouring, best, i
+#ifdef SOLVER_DIAGNOSTICS
+                         , "trying"
+#endif
+                         );
+
             subret = map_solver(rsc, graph, n, ngraph,
                                 subcolouring, difficulty);
 
+#ifdef SOLVER_DIAGNOSTICS
+            if (verbose) {
+                printf("%*sretracting %c in region %d; found %s\n",
+                       2*sc->depth, "", colnames[i], best,
+                       subret == 0 ? "no solutions" :
+                       subret == 1 ? "one solution" : "multiple solutions");
+            }
+#endif
+
             /*
              * If this possibility turned up more than one valid
              * solution, or if it turned up one and we already had
@@ -1055,6 +1364,14 @@ static int map_solver(struct solver_scratch *sc,
         sfree(subcolouring);
         free_scratch(rsc);
 
+#ifdef SOLVER_DIAGNOSTICS
+        if (verbose && sc->depth == 0) {
+            printf("%*s%s found\n",
+                   2*sc->depth, "",
+                   ret == 0 ? "no solutions" :
+                   ret == 1 ? "one solution" : "multiple solutions");
+        }
+#endif
         return ret;
     }
 }
@@ -1239,8 +1556,8 @@ static char *new_game_desc(game_params *params, random_state *rs,
          * Finally, check that the puzzle is _at least_ as hard as
          * required, and indeed that it isn't already solved.
          * (Calling map_solver with negative difficulty ensures the
-         * latter - if a solver which _does nothing_ can't solve
-         * it, it's too easy!)
+         * latter - if a solver which _does nothing_ can solve it,
+         * it's too easy!)
          */
         memcpy(colouring2, colouring, n*sizeof(int));
         if (map_solver(sc, graph, n, ngraph, colouring2,
@@ -1497,6 +1814,9 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
     state->colouring = snewn(n, int);
     for (i = 0; i < n; i++)
        state->colouring[i] = -1;
+    state->pencil = snewn(n, int);
+    for (i = 0; i < n; i++)
+       state->pencil[i] = 0;
 
     state->completed = state->cheated = FALSE;
 
@@ -1601,21 +1921,23 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
 
     /*
      * Analyse the map to find a canonical line segment
-     * corresponding to each edge. These are where we'll eventually
-     * put error markers.
+     * corresponding to each edge, and a canonical point
+     * corresponding to each region. The former are where we'll
+     * eventually put error markers; the latter are where we'll put
+     * per-region flags such as numbers (when in diagnostic mode).
      */
     {
        int *bestx, *besty, *an, pass;
        float *ax, *ay, *best;
 
-       ax = snewn(state->map->ngraph, float);
-       ay = snewn(state->map->ngraph, float);
-       an = snewn(state->map->ngraph, int);
-       bestx = snewn(state->map->ngraph, int);
-       besty = snewn(state->map->ngraph, int);
-       best = snewn(state->map->ngraph, float);
+       ax = snewn(state->map->ngraph + n, float);
+       ay = snewn(state->map->ngraph + n, float);
+       an = snewn(state->map->ngraph + n, int);
+       bestx = snewn(state->map->ngraph + n, int);
+       besty = snewn(state->map->ngraph + n, int);
+       best = snewn(state->map->ngraph + n, float);
 
-       for (i = 0; i < state->map->ngraph; i++) {
+       for (i = 0; i < state->map->ngraph + n; i++) {
            bestx[i] = besty[i] = -1;
            best[i] = 2*(w+h)+1;
            ax[i] = ay[i] = 0.0F;
@@ -1624,11 +1946,12 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
 
        /*
         * We make two passes over the map, finding all the line
-        * segments separating regions. In the first pass, we
-        * compute the _average_ x and y coordinate of all the line
-        * segments separating each pair of regions; in the second
-        * pass, for each such average point, we find the line
-        * segment closest to it and call that canonical.
+        * segments separating regions and all the suitable points
+        * within regions. In the first pass, we compute the
+        * _average_ x and y coordinate of all the points in a
+        * given class; in the second pass, for each such average
+        * point, we find the candidate closest to it and call that
+        * canonical.
         * 
         * Line segments are considered to have coordinates in
         * their centre. Thus, at least one coordinate for any line
@@ -1654,30 +1977,25 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
                        /* right edge */
                        ea[en] = state->map->map[RE * wh + y*w+x];
                        eb[en] = state->map->map[LE * wh + y*w+(x+1)];
-                       if (ea[en] != eb[en]) {
-                           ex[en] = (x+1)*2;
-                           ey[en] = y*2+1;
-                           en++;
-                       }
+                        ex[en] = (x+1)*2;
+                        ey[en] = y*2+1;
+                        en++;
                    }
                    if (y+1 < h) {
                        /* bottom edge */
                        ea[en] = state->map->map[BE * wh + y*w+x];
                        eb[en] = state->map->map[TE * wh + (y+1)*w+x];
-                       if (ea[en] != eb[en]) {
-                           ex[en] = x*2+1;
-                           ey[en] = (y+1)*2;
-                           en++;
-                       }
+                        ex[en] = x*2+1;
+                        ey[en] = (y+1)*2;
+                        en++;
                    }
                    /* diagonal edge */
                    ea[en] = state->map->map[TE * wh + y*w+x];
                    eb[en] = state->map->map[BE * wh + y*w+x];
-                   if (ea[en] != eb[en]) {
-                       ex[en] = x*2+1;
-                       ey[en] = y*2+1;
-                       en++;
-                   }
+                    ex[en] = x*2+1;
+                    ey[en] = y*2+1;
+                    en++;
+
                    if (x+1 < w && y+1 < h) {
                        /* bottom right corner */
                        int oct[8], othercol, nchanges;
@@ -1717,18 +2035,39 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
                            ey[en] = (y+1)*2;
                            en++;
                        }
+
+                        /*
+                         * If there's exactly _one_ region at this
+                         * point, on the other hand, it's a valid
+                         * place to put a region centre.
+                         */
+                        if (othercol < 0) {
+                           ea[en] = eb[en] = oct[0];
+                           ex[en] = (x+1)*2;
+                           ey[en] = (y+1)*2;
+                           en++;
+                        }
                    }
 
                    /*
-                    * Now process the edges we've found, one by
+                    * Now process the points we've found, one by
                     * one.
                     */
                    for (i = 0; i < en; i++) {
                        int emin = min(ea[i], eb[i]);
                        int emax = max(ea[i], eb[i]);
-                       int gindex = 
-                           graph_edge_index(state->map->graph, n,
-                                            state->map->ngraph, emin, emax);
+                       int gindex;
+
+                        if (emin != emax) {
+                            /* Graph edge */
+                            gindex =
+                                graph_edge_index(state->map->graph, n,
+                                                 state->map->ngraph, emin,
+                                                 emax);
+                        } else {
+                            /* Region number */
+                            gindex = state->map->ngraph + emin;
+                        }
 
                        assert(gindex >= 0);
 
@@ -1763,7 +2102,7 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
                }
 
            if (pass == 0) {
-               for (i = 0; i < state->map->ngraph; i++)
+               for (i = 0; i < state->map->ngraph + n; i++)
                    if (an[i] > 0) {
                        ax[i] /= an[i];
                        ay[i] /= an[i];
@@ -1771,8 +2110,15 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
            }
        }
 
-       state->map->edgex = bestx;
-       state->map->edgey = besty;
+       state->map->edgex = snewn(state->map->ngraph, int);
+       state->map->edgey = snewn(state->map->ngraph, int);
+        memcpy(state->map->edgex, bestx, state->map->ngraph * sizeof(int));
+        memcpy(state->map->edgey, besty, state->map->ngraph * sizeof(int));
+
+       state->map->regionx = snewn(n, int);
+       state->map->regiony = snewn(n, int);
+        memcpy(state->map->regionx, bestx + state->map->ngraph, n*sizeof(int));
+        memcpy(state->map->regiony, besty + state->map->ngraph, n*sizeof(int));
 
        for (i = 0; i < state->map->ngraph; i++)
            if (state->map->edgex[i] < 0) {
@@ -1789,6 +2135,8 @@ static game_state *new_game(midend *me, game_params *params, char *desc)
        sfree(ay);
        sfree(an);
        sfree(best);
+       sfree(bestx);
+       sfree(besty);
     }
 
     return state;
@@ -1801,6 +2149,8 @@ static game_state *dup_game(game_state *state)
     ret->p = state->p;
     ret->colouring = snewn(state->p.n, int);
     memcpy(ret->colouring, state->colouring, state->p.n * sizeof(int));
+    ret->pencil = snewn(state->p.n, int);
+    memcpy(ret->pencil, state->pencil, state->p.n * sizeof(int));
     ret->map = state->map;
     ret->map->refcount++;
     ret->completed = state->completed;
@@ -1817,6 +2167,8 @@ static void free_game(game_state *state)
        sfree(state->map->immutable);
        sfree(state->map->edgex);
        sfree(state->map->edgey);
+       sfree(state->map->regionx);
+       sfree(state->map->regiony);
        sfree(state->map);
     }
     sfree(state->colouring);
@@ -1891,6 +2243,7 @@ static char *game_text_format(game_state *state)
 struct game_ui {
     int drag_colour;                   /* -1 means no drag active */
     int dragx, dragy;
+    int show_numbers;
 };
 
 static game_ui *new_ui(game_state *state)
@@ -1898,6 +2251,7 @@ static game_ui *new_ui(game_state *state)
     game_ui *ui = snew(game_ui);
     ui->dragx = ui->dragy = -1;
     ui->drag_colour = -2;
+    ui->show_numbers = FALSE;
     return ui;
 }
 
@@ -1922,15 +2276,21 @@ static void game_changed_state(game_ui *ui, game_state *oldstate,
 
 struct game_drawstate {
     int tilesize;
-    unsigned short *drawn, *todraw;
+    unsigned long *drawn, *todraw;
     int started;
     int dragx, dragy, drag_visible;
     blitter *bl;
 };
 
 /* Flags in `drawn'. */
-#define ERR_BASE 0x0080
-#define ERR_MASK 0xFF80
+#define ERR_BASE      0x00800000L
+#define ERR_MASK      0xFF800000L
+#define PENCIL_T_BASE 0x00080000L
+#define PENCIL_T_MASK 0x00780000L
+#define PENCIL_B_BASE 0x00008000L
+#define PENCIL_B_MASK 0x00078000L
+#define PENCIL_MASK   0x007F8000L
+#define SHOW_NUMBERS  0x00004000L
 
 #define TILESIZE (ds->tilesize)
 #define BORDER (TILESIZE)
@@ -1961,6 +2321,14 @@ static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
 {
     char buf[80];
 
+    /*
+     * Enable or disable numeric labels on regions.
+     */
+    if (button == 'l' || button == 'L') {
+        ui->show_numbers = !ui->show_numbers;
+        return "";
+    }
+
     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
        int r = region_from_coords(state, ds, x, y);
 
@@ -2000,7 +2368,11 @@ static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
         if (state->colouring[r] == c)
             return "";                 /* don't _need_ to change this region */
 
-       sprintf(buf, "%c:%d", (int)(c < 0 ? 'C' : '0' + c), r);
+       if (button == RIGHT_RELEASE && state->colouring[r] >= 0)
+           return "";                 /* can't pencil on a coloured region */
+
+       sprintf(buf, "%s%c:%d", (button == RIGHT_RELEASE ? "p" : ""),
+                (int)(c < 0 ? 'C' : '0' + c), r);
        return dupstr(buf);
     }
 
@@ -2014,12 +2386,30 @@ static game_state *execute_move(game_state *state, char *move)
     int c, k, adv, i;
 
     while (*move) {
+        int pencil = FALSE;
+
        c = *move;
+        if (c == 'p') {
+            pencil = TRUE;
+            c = *++move;
+        }
        if ((c == 'C' || (c >= '0' && c < '0'+FOUR)) &&
            sscanf(move+1, ":%d%n", &k, &adv) == 1 &&
            k >= 0 && k < state->p.n) {
            move += 1 + adv;
-           ret->colouring[k] = (c == 'C' ? -1 : c - '0');
+            if (pencil) {
+               if (ret->colouring[k] >= 0) {
+                   free_game(ret);
+                   return NULL;
+               }
+                if (c == 'C')
+                    ret->pencil[k] = 0;
+                else
+                    ret->pencil[k] ^= 1 << (c - '0');
+            } else {
+                ret->colouring[k] = (c == 'C' ? -1 : c - '0');
+                ret->pencil[k] = 0;
+            }
        } else if (*move == 'S') {
            move++;
            ret->cheated = TRUE;
@@ -2134,10 +2524,10 @@ static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
     int i;
 
     ds->tilesize = 0;
-    ds->drawn = snewn(state->p.w * state->p.h, unsigned short);
+    ds->drawn = snewn(state->p.w * state->p.h, unsigned long);
     for (i = 0; i < state->p.w * state->p.h; i++)
-       ds->drawn[i] = 0xFFFF;
-    ds->todraw = snewn(state->p.w * state->p.h, unsigned short);
+       ds->drawn[i] = 0xFFFFL;
+    ds->todraw = snewn(state->p.w * state->p.h, unsigned long);
     ds->started = FALSE;
     ds->bl = NULL;
     ds->drag_visible = FALSE;
@@ -2191,10 +2581,15 @@ static void draw_square(drawing *dr, game_drawstate *ds,
                        int x, int y, int v)
 {
     int w = params->w, h = params->h, wh = w*h;
-    int tv, bv, xo, yo, errs;
+    int tv, bv, xo, yo, errs, pencil, i, j, oldj;
+    int show_numbers;
 
     errs = v & ERR_MASK;
     v &= ~ERR_MASK;
+    pencil = v & PENCIL_MASK;
+    v &= ~PENCIL_MASK;
+    show_numbers = v & SHOW_NUMBERS;
+    v &= ~SHOW_NUMBERS;
     tv = v / FIVE;
     bv = v % FIVE;
 
@@ -2225,6 +2620,39 @@ static void draw_square(drawing *dr, game_drawstate *ds,
     }
 
     /*
+     * Draw `pencil marks'. Currently we arrange these in a square
+     * formation, which means we may be in trouble if the value of
+     * FOUR changes later...
+     */
+    assert(FOUR == 4);
+    for (yo = 0; yo < 4; yo++)
+       for (xo = 0; xo < 4; xo++) {
+           int te = map->map[TE * wh + y*w+x];
+           int e, ee, c;
+
+           e = (yo < xo && yo < 3-xo ? TE :
+                yo > xo && yo > 3-xo ? BE :
+                xo < 2 ? LE : RE);
+           ee = map->map[e * wh + y*w+x];
+
+           c = (yo & 1) * 2 + (xo & 1);
+
+           if (!(pencil & ((ee == te ? PENCIL_T_BASE : PENCIL_B_BASE) << c)))
+               continue;
+
+           if (yo == xo &&
+               (map->map[TE * wh + y*w+x] != map->map[LE * wh + y*w+x]))
+               continue;              /* avoid TL-BR diagonal line */
+           if (yo == 3-xo &&
+               (map->map[TE * wh + y*w+x] != map->map[RE * wh + y*w+x]))
+               continue;              /* avoid BL-TR diagonal line */
+
+           draw_rect(dr, COORD(x) + (5*xo+1)*TILESIZE/20,
+                     COORD(y) + (5*yo+1)*TILESIZE/20,
+                     4*TILESIZE/20, 4*TILESIZE/20, COL_0 + c);
+       }
+
+    /*
      * Draw the grid lines, if required.
      */
     if (x <= 0 || map->map[RE*wh+y*w+(x-1)] != map->map[LE*wh+y*w+x])
@@ -2246,6 +2674,31 @@ static void draw_square(drawing *dr, game_drawstate *ds,
                           (COORD(x)*2+TILESIZE*xo)/2,
                           (COORD(y)*2+TILESIZE*yo)/2);
 
+    /*
+     * Draw region numbers, if desired.
+     */
+    if (show_numbers) {
+        oldj = -1;
+        for (i = 0; i < 2; i++) {
+            j = map->map[(i?BE:TE)*wh+y*w+x];
+            if (oldj == j)
+                continue;
+            oldj = j;
+
+            xo = map->regionx[j] - 2*x;
+            yo = map->regiony[j] - 2*y;
+            if (xo >= 0 && xo <= 2 && yo >= 0 && yo <= 2) {
+                char buf[80];
+                sprintf(buf, "%d", j);
+                draw_text(dr, (COORD(x)*2+TILESIZE*xo)/2,
+                          (COORD(y)*2+TILESIZE*yo)/2,
+                          FONT_VARIABLE, 3*TILESIZE/5,
+                          ALIGN_HCENTRE|ALIGN_VCENTRE,
+                          COL_GRID, buf);
+            }
+        }
+    }
+
     unclip(dr);
 
     draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
@@ -2324,6 +2777,21 @@ static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
 
             v = tv * FIVE + bv;
 
+            /*
+             * Add pencil marks.
+             */
+           for (i = 0; i < FOUR; i++) {
+               if (state->colouring[state->map->map[TE * wh + y*w+x]] < 0 &&
+                   (state->pencil[state->map->map[TE * wh + y*w+x]] & (1<<i)))
+                   v |= PENCIL_T_BASE << i;
+               if (state->colouring[state->map->map[BE * wh + y*w+x]] < 0 &&
+                   (state->pencil[state->map->map[BE * wh + y*w+x]] & (1<<i)))
+                   v |= PENCIL_B_BASE << i;
+           }
+
+            if (ui->show_numbers)
+                v |= SHOW_NUMBERS;
+
            ds->todraw[y*w+x] = v;
        }
 
@@ -2540,7 +3008,7 @@ static void game_print(drawing *dr, game_state *state, int tilesize)
                    else
                        d2 = i;
                }
-/* printf("%% %d,%d r=%d: d1=%d d2=%d lastdir=%d\n", x, y, r, d1, d2, lastdir); */
+
            assert(d1 != -1 && d2 != -1);
            if (d1 == lastdir)
                d1 = d2;
@@ -2613,3 +3081,145 @@ const struct game thegame = {
     FALSE, game_timing_state,
     0,                                /* mouse_priorities */
 };
+
+#ifdef STANDALONE_SOLVER
+
+#include <stdarg.h>
+
+void frontend_default_colour(frontend *fe, float *output) {}
+void draw_text(drawing *dr, int x, int y, int fonttype, int fontsize,
+               int align, int colour, char *text) {}
+void draw_rect(drawing *dr, int x, int y, int w, int h, int colour) {}
+void draw_line(drawing *dr, int x1, int y1, int x2, int y2, int colour) {}
+void draw_polygon(drawing *dr, int *coords, int npoints,
+                  int fillcolour, int outlinecolour) {}
+void draw_circle(drawing *dr, int cx, int cy, int radius,
+                 int fillcolour, int outlinecolour) {}
+void clip(drawing *dr, int x, int y, int w, int h) {}
+void unclip(drawing *dr) {}
+void start_draw(drawing *dr) {}
+void draw_update(drawing *dr, int x, int y, int w, int h) {}
+void end_draw(drawing *dr) {}
+blitter *blitter_new(drawing *dr, int w, int h) {return NULL;}
+void blitter_free(drawing *dr, blitter *bl) {}
+void blitter_save(drawing *dr, blitter *bl, int x, int y) {}
+void blitter_load(drawing *dr, blitter *bl, int x, int y) {}
+int print_mono_colour(drawing *dr, int grey) { return 0; }
+int print_rgb_colour(drawing *dr, int hatch, float r, float g, float b)
+{ return 0; }
+void print_line_width(drawing *dr, int width) {}
+
+void fatal(char *fmt, ...)
+{
+    va_list ap;
+
+    fprintf(stderr, "fatal error: ");
+
+    va_start(ap, fmt);
+    vfprintf(stderr, fmt, ap);
+    va_end(ap);
+
+    fprintf(stderr, "\n");
+    exit(1);
+}
+
+int main(int argc, char **argv)
+{
+    game_params *p;
+    game_state *s;
+    char *id = NULL, *desc, *err;
+    int grade = FALSE;
+    int ret, diff, really_verbose = FALSE;
+    struct solver_scratch *sc;
+    int i;
+
+    while (--argc > 0) {
+        char *p = *++argv;
+        if (!strcmp(p, "-v")) {
+            really_verbose = TRUE;
+        } else if (!strcmp(p, "-g")) {
+            grade = TRUE;
+        } else if (*p == '-') {
+            fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
+            return 1;
+        } else {
+            id = p;
+        }
+    }
+
+    if (!id) {
+        fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
+        return 1;
+    }
+
+    desc = strchr(id, ':');
+    if (!desc) {
+        fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
+        return 1;
+    }
+    *desc++ = '\0';
+
+    p = default_params();
+    decode_params(p, id);
+    err = validate_desc(p, desc);
+    if (err) {
+        fprintf(stderr, "%s: %s\n", argv[0], err);
+        return 1;
+    }
+    s = new_game(NULL, p, desc);
+
+    sc = new_scratch(s->map->graph, s->map->n, s->map->ngraph);
+
+    /*
+     * When solving an Easy puzzle, we don't want to bother the
+     * user with Hard-level deductions. For this reason, we grade
+     * the puzzle internally before doing anything else.
+     */
+    ret = -1;                         /* placate optimiser */
+    for (diff = 0; diff < DIFFCOUNT; diff++) {
+        for (i = 0; i < s->map->n; i++)
+            if (!s->map->immutable[i])
+                s->colouring[i] = -1;
+       ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
+                         s->colouring, diff);
+       if (ret < 2)
+           break;
+    }
+
+    if (diff == DIFFCOUNT) {
+       if (grade)
+           printf("Difficulty rating: harder than Hard, or ambiguous\n");
+       else
+           printf("Unable to find a unique solution\n");
+    } else {
+       if (grade) {
+           if (ret == 0)
+               printf("Difficulty rating: impossible (no solution exists)\n");
+           else if (ret == 1)
+               printf("Difficulty rating: %s\n", map_diffnames[diff]);
+       } else {
+           verbose = really_verbose;
+            for (i = 0; i < s->map->n; i++)
+                if (!s->map->immutable[i])
+                    s->colouring[i] = -1;
+            ret = map_solver(sc, s->map->graph, s->map->n, s->map->ngraph,
+                             s->colouring, diff);
+           if (ret == 0)
+               printf("Puzzle is inconsistent\n");
+           else {
+                int col = 0;
+
+                for (i = 0; i < s->map->n; i++) {
+                    printf("%5d <- %c%c", i, colnames[s->colouring[i]],
+                           (col < 6 && i+1 < s->map->n ? ' ' : '\n'));
+                    if (++col == 7)
+                        col = 0;
+                }
+            }
+       }
+    }
+
+    return 0;
+}
+
+#endif