// 4 color theorem

/* This is an earlier version of the software that has a lot more features,
features that we don't really need to prove the theorem.
But I couldn't bear to throw it away.
If there is a bug in 4ct.c, we might need to resurrect some of these features. */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <memory.h>
#include <malloc.h>

/*********************************************************************
Before you try to decipher this code, have a look at p555,
a typical input file that describes a subgraph to color.
Also review http://www.mathreference.com/gph-planar,5color.html

type make to compile.

Usage is 4ct inputfile(s)
Example: 4ct p555
*********************************************************************/

typedef unsigned char uchar;

// set these to 1 for lots of debug output
#define DEBUGLINES 0
#define DEBUGCONFIG 0

// A kinder, gentler debug than the above, and can be set at the command line.
static int debug;

// Internal points are the actual subgraph described by the file.
// Border is the ring around this subgraph.
#define MAXINTERNAL 32
#define MAXBORDER 32

// number of internal points, and number of points on the border
static int ninternal, nborder;

// Edges, assumes average degree of 7 or less.
#define MAXCONNECT (MAXINTERNAL*7)
// Symmetries, up to dihedral 6
#define MAXROTATE 24

// error and abort
static void eprint(const char *msg, int arg)
{
    fprintf(stderr, msg, arg);
    fprintf(stderr, "\n");
    exit(1);
}

static void eprints(const char *msg, const char *arg)
{
    fprintf(stderr, msg, arg);
    fprintf(stderr, "\n");
    exit(1);
}

static void *emalloc(unsigned int n)
{
    void *s = malloc(n);
    if(!s) eprint("could not allocate %d bytes", n);
    return s;
}

static void *erealloc(void *s, unsigned int n)
{
    s = realloc(s, n);
    if(!s) eprint("could not reallocate %d bytes", n);
    return s;
}

static char *nextLine(FILE * f)
{
    static char line[200];
    while(1) {
        if(!fgets(line, sizeof (line), f)) return 0;
        if(line[0] == '#' || line[0] == '\n') continue;
        return line;
    }
}

// A list of internal points that make the perimeter.
// The border lies just outside the perimeter.
static uchar perimeter[MAXINTERNAL];
static int nperim;

static uchar rots[MAXROTATE][MAXBORDER];
static int nrots;

static uchar *patterns; // allocated
static uchar *patternEnd;
static int maxpattern, npattern;
static int fp12, fp13, fp31, fp32, fp34;

// Set to 1 for each pattern that is colorable.
static uchar *colorable;

// which uncolorable patterns are still allowed by lines and sewing
// Each ushort is a bitmask, which rotations are matchable

// list of connections. [0] to [1]
// conections among vertices in the input graph have a base of MAXBORDAR.
static uchar connections[MAXCONNECT][2];
static int nedges;

// Print a border for debugging purposes.
static void printBorder(const uchar * b, int r)
{
    for(int i = 0; i < nborder; ++i)
        printf("%d", b[i]);
    if(r) {
        printf(" r ");
        for(int i = 0; i < nborder; ++i)
            printf("%d", b[rots[r][i]]);
    }
    printf("\n");
}

static void goodBad(void)
{
    int i;
    const uchar *p;
    if(!debug) return;
    puts("good");
    for(i = 0; i < npattern; ++i) {
        if(!colorable[i]) continue;
        p = patterns + i * nborder;
        printBorder(p, 0);
    }
    puts("bad");
    for(i = 0; i < npattern; ++i) {
        if(colorable[i]) continue;
        p = patterns + i * nborder;
        printBorder(p, 0);
    }
    puts("end");
}

static void printInternal(const uchar * b)
{
    for(int i = 0; i < ninternal; ++i)
        printf("%d", b[i]);
    printf("\n");
}

// Make the first color on the border red, next one blue, etc.
static void normalizeColors(uchar * p)
{
    int nc = 0;
    uchar list[8];
    memset(list, 0, sizeof (list));
    for(int i = 0; i < nborder; ++i) {
        uchar c = p[i];
        if(!list[c]) list[c] = ++nc;
        p[i] = list[c];
    }
}

static void rotatePattern(const uchar * p, const uchar * r, uchar * dest)
{
    if(r == rots[0]) {
// the trivial rotation
        memcpy(dest, p, nborder);
        return;
    }
    for(int i = 0; i < nborder; ++i)
        dest[i] = p[r[i]];
}

// generate all rotations from the initial rotation and reflection.
// Not very eficient, but only done once in the beginning,
// and makes a dozen permutations at most.
static void buildRotations(void)
{
    uchar dest[MAXBORDER];
    int i, j, k, change = 1;
    while(change) {
        change = 0;
        for(i = 0; i < nrots; ++i) {
            for(j = i; j < nrots; ++j) {
                rotatePattern(rots[i], rots[j], dest);
                for(k = 0; k < nrots; ++k)
                    if(!memcmp(rots[k], dest, nborder)) break;
                if(k < nrots) continue;
                if(nrots == MAXROTATE)
                    eprint("too many rotations, limit %d", MAXROTATE);
                memcpy(rots[nrots], dest, nborder);
                ++nrots;
                change = 1;
            }
        }
    }

    printf("%d rotations\n", nrots);
    if(!debug) return;

    for(i=0; i<nrots; ++i) {
        for(j=0; j<nborder; ++j) {
            if(j) printf(" ");
            printf("%d", rots[i][j]);
        }
        printf("\n");
    }
}

// Add an edge from an internal point to a point on the border
// Internal point number is bumped up by MAXBORDER.
static void addEdge(int u, int v)
{
    if(nedges == MAXCONNECT)
        eprint(" too many connections, limit %d", MAXCONNECT);
    if(debug)
        printf("%c %d\n", u + (u < 26 ? 'a' : 'A' - 26), v);
    connections[nedges][0] = u + MAXBORDER;
    connections[nedges][1] = v;
    ++nedges;
}

// turn a into 0, d into 3, A into 26, etc
static int letterInternal(const char *line, char c)
{
// line is here only for error messages
    int j;
    if(islower(c)) j = c - 'a';
    else if(isupper(c)) j = c - 'A' + 26;
    else eprints("letter expected in line %s", line);
    if(j >= ninternal) eprint("vertex %c is out of range", c);
    return j;
}

static void readGraph(const char *filename)
{
    char *line, *s;
    int i, j;
    int shift = 0, reflect = 0;
    char rowmode = 0;
    int edeg; // external degree
    int edeg0; // external degree of first vertex
    FILE *f;
// The degree of each internal point.
    uchar degree[MAXINTERNAL];
    uchar extdegree[MAXINTERNAL];

    f = fopen(filename, "r");
    if(!f) eprints("cannot open file %s", filename);

    line = nextLine(f);
    if(!line) eprint("empty file", 0);
    ninternal = strtol(line, &s, 10);
    if(ninternal > MAXINTERNAL || ninternal <= 0)
        eprint("too many internal points", ninternal);

    if(*s == '+')
        shift = strtol(s + 1, &s, 10);

    if(*s == '^')
        reflect = 1;

    line = nextLine(f);
    if(!line) eprint("list of perimeter points and their degrees is expected", 0);
    s = line;
    if(*s == ';') {
        ++s, rowmode = 1;
        if(shift > 2) eprint("row mode is not compatible with %d rotations", shift);
    }
    i = 0;
    while(isalpha(*s)) {
        if(i >= ninternal) eprint("too many points on the perimeter, as set by %d", ninternal);
        perimeter[i] = letterInternal(line, *s);
        for(j = 0; j < i; ++j)
            if(perimeter[j] == perimeter[i]) eprint("perimeter point %c is repeated", *s);
        degree[i] = strtol(s + 1, &s, 10);
        if(degree[i] < 5 || degree[i] > 15)
            eprint("degree %d out of range, please use 5 to 15", degree[i]);

        if(i) {
            connections[nedges][0] = perimeter[i - 1] + MAXBORDER;
            connections[nedges][1] = perimeter[i] + MAXBORDER;
            ++nedges;
        }

        while(*s == ' ') ++s;
        ++i;
    }
    nperim = i;

    if(i > 2 && !rowmode) {
// another edge completes the circle
        connections[nedges][0] = perimeter[i - 1] + MAXBORDER;
        connections[nedges][1] = perimeter[0] + MAXBORDER;
        ++nedges;
    }

    if(*s != '\n') eprint("unexpected character %c in perimeter description", *s);
    if(nperim == 2 && !rowmode) eprint("2 vertices requires row mode", 0);

    while(line = nextLine(f)) {
        if(rowmode) eprints("line %s after perimeter in row mode", line);
        char preletter = 0;
        char firstletter = 0;
        uchar fan = 0;
// fan set to 1 for   a>bcd which connects a to b c and d, like a fan out
        j = 0;
        s = line;
        while(isalpha(*s)) {
            if(preletter) {
                if(nedges == MAXCONNECT) eprint(" too many connections, limit %d", MAXCONNECT);
                connections[nedges][0] = letterInternal(line, (fan ? firstletter : preletter)) + MAXBORDER;
                connections[nedges][1] = letterInternal(line, *s) + MAXBORDER;
                ++nedges;
            }
            preletter = *s;
            if(!j) firstletter = *s;
            ++j, ++s;
            while(*s == ' ') ++s;
            if(j == 1 && *s == '>') {
                fan = 1;
                ++s;
                while(*s == ' ') ++s;
            }
        }
        if(*s != '\n') eprints("syntax error in line %s", line);
        if(j > 2 && !fan) {
            if(nedges == MAXCONNECT) eprint(" too many connections, limit %d", MAXCONNECT);
// another edge completes the circle
            connections[nedges][0] = letterInternal(line, preletter) + MAXBORDER;
            connections[nedges][1] = letterInternal(line, firstletter) + MAXBORDER;
            ++nedges;
        }

// check for duplicates
        for(i=0; i<nedges; ++i) {
            for(j=i+1; j<nedges; ++j) {
                if(connections[i][0] == connections[j][0] &&
                connections[i][1] == connections[j][1] ||
                connections[i][0] == connections[j][1] &&
                connections[i][1] == connections[j][0])
                    eprints("duplicate connections at %s", line);
            }
        }
    }

// find the internal degree of each point and subtract from degree[i]
    for(i = 0; i < nperim; ++i) {
        int ideg = 0;
        for(j = 0; j < nedges; ++j) {
            uchar u = connections[j][0];
            uchar v = connections[j][1];
            if(u < MAXBORDER || v < MAXBORDER) continue;
            u -= MAXBORDER, v -= MAXBORDER;
            if(u == perimeter[i] || v == perimeter[i]) ++ideg;
        }
        if(ideg >= degree[i]) {
            fprintf(stderr, "internal degree of %c is %d; should be less than %d\n",
            perimeter[i] + (perimeter[i] < 26 ? 'a' : 'A' - 26), ideg, degree[i]);
            exit(1);
        }
        edeg = extdegree[i] = degree[i] - ideg;
    }

// Set up the border.
    if(rowmode) {
// everything in the row is connected to vertex 0
        for(i = 0; i < nperim; ++i)
            addEdge(perimeter[i], 0);
        addEdge(perimeter[i - 1], 1);
        nborder = 2;
        for(i = nperim - 1; i >= 0; --i) {
            for(j = 0; j < degree[i] - 3; ++j) {
                addEdge(perimeter[i], nborder);
                ++nborder;
            }
            --nborder;
        }
        ++nborder;
        addEdge(perimeter[0], nborder);
        ++nborder;

    } else {

        for(i = 0; i < nperim; ++i) {
            edeg = extdegree[i];
            if(!i) { // first vertex
                edeg0 = edeg;
                edeg = (edeg + 1) / 2;
            } else {
                addEdge(perimeter[i], nborder - 1);
                --edeg;
            }

            while(edeg) {
                if(nborder >= MAXBORDER) eprint("too many border points, limit %d", MAXBORDER);
                addEdge(perimeter[i], nborder);
                ++nborder, --edeg;
            }
        }

// Revisit the first vertex.
        edeg = edeg0 / 2;
        if(!edeg) {
            if(nborder > 1) {
// special case; we shouldn't have created the last vertex
                --nborder;
                for(i=nedges-1; connections[i][1] == nborder; --i)
                    connections[i][1] = 0;
                if(debug) printf("replace point %d with 0\n", nborder);
            }
        } else {
            addEdge(perimeter[0], nborder - 1);
            --edeg;
        }

        while(edeg) {
            if(nborder >= MAXBORDER) eprint("too many border points, limit %d", MAXBORDER);
            addEdge(perimeter[0], nborder);
            ++nborder, --edeg;
        }
    }

    printf("%d border points\n", nborder);

// The identity rotation
    for(i = 0; i < nborder; ++i)
        rots[0][i] = i;
    ++nrots;

    if(shift) {
        if(nperim % shift) eprint("invalid perimeter rotation for a ring of size %d", nperim);
        if(nborder % shift) eprint("invalid border rotation for a ring of size %d", nborder);
        for(i = 0; i < nperim - nperim / shift; ++i)
            if(degree[i] != degree[i + nperim / shift])
                eprint("rotation through %d does not preserve perimeter degree", shift);
        for(i = 0; i < nperim - nperim / shift; ++i)
            if(extdegree[i] != extdegree[i + nperim / shift])
                eprint("rotation through %d does not preserve external degree", shift);
        for(i = 0; i < nborder; ++i)
            rots[nrots][i] = (i + nborder / shift) % nborder;
        ++nrots;
    }

    if(reflect) {
        if(rowmode) {
            for(i = 0; i < nperim; ++i)
                if(degree[i] != degree[nperim - 1 - i])
                    eprint("reflection does not preserv row degree", 0);
            goto onzero;
        }

        for(i = 1; i < nperim; ++i)
            if(degree[i] != degree[nperim - i]) break;
        if(i == nperim) {
            if(edeg0 & 1) {
onzero:
                printf("pivot point is %d\n", 0);
                rots[nrots][0] = 0;
                for(i = 1; i < nborder; ++i)
                    rots[nrots][i] = nborder - i;
            } else {
                printf("pivot point is %d-0\n", nborder - 1);
                for(i = 0; i < nborder; ++i)
                    rots[nrots][i] = nborder - 1 - i;
            }
        } else {
            for(i = 0; i < nperim; ++i)
                if(degree[i] != degree[nperim - 1 - i]) break;
            if(i < nperim) eprint("reflection does not preserv perimeter degree", 0);
// back up to the far end of the border when it first
// connectes to the first vertex of the perimeter.
            for(i = nedges - 1; connections[i][0] == perimeter[0] + MAXBORDER; --i) ;
            j = connections[i][1];
            printf("pivot point is %d\n", j);
            for(i = 0; i < nborder; ++i) {
                int w = (j + j - i) % nborder;
                if(w < 0) w += nborder;
                rots[nrots][i] = w;
            }
        }

        ++nrots;
    }

    buildRotations();
}

// Find the canonical pattern for a given pattern.
// This is the first, lexicographically, in its equivalence class.
// Leave the result in equivalent[].
static uchar equivalent[MAXBORDER];
static void findEquivalentPattern(const uchar * p)
{
    uchar temp[MAXBORDER];
    equivalent[0] = 5;
    for(int j = 0; j < nrots; ++j) {
        rotatePattern(p, rots[j], temp);
        normalizeColors(temp);
        if(memcmp(temp, equivalent, nborder) < 0)
            memcpy(equivalent, temp, nborder);
    }
}

// patterns are a function of the border, and rotations of the border, having
// nothing to do with the graph inside. This grows as 3^n
// where n is border length - 2.
static void buildPatterns(void)
{
    int level, i;
    uchar b[MAXBORDER];

// make room for the first 1000
    maxpattern = 1000;
    patterns = emalloc(maxpattern * nborder);
    patternEnd = patterns + maxpattern * nborder;

// Start with 2 prescribed colors, like red and blue.
    b[0] = 1, b[1] = 2;
    level = 1;

push:
    if(++level == nborder) {
        findEquivalentPattern(b);
        if(!memcmp(b, equivalent, nborder)) {
            if(npattern == maxpattern) {
                if(patternEnd - patterns >= 40000000)
                    eprint("too many patterns in ram; you have to redesign the program", 0);
                maxpattern = maxpattern * 3 / 2;
                patterns = erealloc(patterns, maxpattern * nborder);
                patternEnd = patterns + maxpattern * nborder;
            }
            memcpy(patterns + npattern * nborder, b, nborder);
            ++npattern;
        }
        goto pop;
    }
    b[level] = 0;

next:
    if(++b[level] == 5) goto pop;
    if(b[level] == b[level - 1]) goto next;
    if(level == nborder - 1 && b[level] == 1) goto next;
    goto push;

pop:
    if(--level > 1) goto next;
    printf("%d patterns\n", npattern);

    fp12 = fp13 = fp31 = fp32 = fp34 = -1;
    for(i=0; i<npattern; ++i) {
        uchar u, v;
        const uchar *s = patterns + i * nborder;
        u = s[2], v = s[3];
        if(u == 1 && v == 2 && fp12 < 0) fp12 = i;
        if(u == 1 && v == 3 && fp13 < 0) fp13 = i;
        if(u == 3 && v == 1 && fp31 < 0) fp31 = i;
        if(u == 3 && v == 2 && fp32 < 0) fp32 = i;
        if(u == 3 && v == 4 && fp34 < 0) fp34 = i;
    }
    if(fp12 < 0) eprint("no fp12", 0);
    if(fp13 < 0) eprint("no fp13", 0);
    if(fp31 < 0) eprint("no fp31", 0);
    if(fp34 < 0) fp34 = npattern;
    if(fp32 < 0) fp32 = fp34;
}

// Color the internal points based on a given boundary.
// Return true if it can be done.
static int colorInternal(const uchar * b)
{
    uchar x[MAXINTERNAL];
    uchar c, v;
    int level = -1;

push:
    if(++level == ninternal) return 1;
    x[level] = 0;

next:
    c = ++x[level];
    if(c == 5) goto pop;

    v = MAXBORDER + level;
// v is a representation of the vertex in our graph, within the list of edges.
    for(int k = 0; k < nedges; ++k) {
        uchar other;
        if(connections[k][0] == v) other = connections[k][1];
        else if(connections[k][1] == v) other = connections[k][0];
        else continue;
        if(other > v) continue; // not yet colored
// other has to be different from c
        if(other < MAXBORDER && b[other] == c) goto next;
        if(other >= MAXBORDER && x[other - MAXBORDER] == c) goto next;
    }
    goto push;

pop:
    if(--level >= 0) goto next;
    return 0;
}

static const uchar *cp; // current pattern
static uchar cpc[MAXBORDER]; // current pattern copy

// Is the equivalent pattern (of the copy) colorable?
static int equivalentColorable(void)
{
    int i, l, r; // for binary search
    int d;
    int nb4 = nborder-4;
    const uchar *eq;

    findEquivalentPattern(cpc);

    switch(equivalent[2]*8 + equivalent[3]) {
    case 012: l = fp12-1; r = fp13; break;
    case 013: l = fp13-1; r = fp31; break;
    case 031: l = fp31-1; r = fp32; break;
    case 032: l = fp32-1; r = fp34; break;
    case 034: l = fp34-1; r = npattern; break;
    default: eprint("bad 3 4 colors in normalized pattern", 0);
    }

    eq = equivalent + 4;
    while(r - l > 1) {
        i = (l + r) / 2;
        d = memcmp(eq, patterns + i * nborder+4, nb4);
        if(!d) return colorable[i];
        if(d < 0) r = i; else l = i;
    }

    eprint("equivalent pattern not found", 0);
}

// swap c1 and c2, or c3 and c4
static uchar c1, c2, c3, c4;
static uchar band[MAXBORDER];
static uchar bandstart[MAXBORDER];
static int nbands;

static void findBands(void)
{
    int i;
// first chunk of the border belongs to band 1
    nbands = 1;
    band[0] = 1;
    bandstart[1] = 0;
    for(i = 1; i < nborder; ++i) {
        uchar u = cp[i], v = cp[i - 1];
        if(u == c4) u = c3;
        if(u == c2) u = c1;
        if(v == c4) v = c3;
        if(v == c2) v = c1;
        if(v != u) {
            ++nbands; // start of new band
            bandstart[nbands] = i;
        }
        band[i] = nbands;
    }

// rbrbrbrb or rbrygy
    if(nbands <= 2) return;
// starts with r or b, ends in y or g
    if(!(nbands & 1)) return;

// last band is really part of the first  rbrygyb
    for(i = nborder - 1; band[i] == nbands; --i)
        band[i] = 1;
    --nbands;
    ++i;
    bandstart[1] = i;
}

// act within the copy of the color pattern
static void swapBand(int n)
{
    uchar total;
    ++n;
    int j = bandstart[n];
    if(cpc[j] == c1 || cpc[j] == c2) total = c1 + c2;
    else total = c3 + c4;
    while(band[j] == n) {
        cpc[j] = total - cpc[j];
        if(++j == nborder) j = 0;
    }
}

#define cpRestore() memcpy(cpc, cp, nborder)

static int chainColorable2(void)
{
    int i, j, rc;
    int start, start1, start_1, start2, start_2, start3, start_3, start4;

    findBands();
    int halfband = nbands / 2;

// If all rbrbrbrb and we swap r and b, nothing to do.
// If rbrbrbgygygy and we swap r and b, or g and y, nothing to do.
    if(nbands < 4) return 0;
// beyond the limits of this program - no way should we have 29 bands.
    if(nbands > 28) {
        printf("%d bands is beyond limit\n", nbands);
        return 0;
    }

    if(nbands == 4) {
        cpRestore();
        swapBand(0);
        rc = equivalentColorable();
        if(!rc) return 0;
        cpRestore();
        swapBand(1);
        rc = equivalentColorable();
        if(rc && debug) {
            printf("%d bands %d%d 0f ", nbands, c1, c2);
            printBorder(cp, 0);
        }
        return rc;
    }

    int yescount = 0, m = 0;
// m is a mask of the single arcs that flip and work
    for(i=0; i<nbands; ++i) {
        cpRestore();
        swapBand(i);
        yescount += rc = equivalentColorable();
        if(rc) m |= (1<<i);
    }

    if(nbands == 6) {
        if(yescount < 3) return 0;
        if(debug) {
            printf("6 bands %d%d %02x ", c1, c2, m);
            printBorder(cp, 0);
        }
        if(yescount >= 5) return 1;
        if((m&7) == 7 || (m&0xe) == 0xe || (m&0x1c) == 0x1c ||
        (m&0x38) == 0x38 || (m&0x31) == 0x31 || (m&0x23) == 0x23)
            return 1;
        if(yescount == 3) return 0;
// now yescount is 4 but not 3 in a row
        if(!(m&1)) i = 0;
        if(!(m&2)) i = 1;
        if(!(m&4)) i = 2;
        cpRestore();
        swapBand(i);
        swapBand(i+3);
        rc = equivalentColorable();
        if(rc && debug) printf("across,%d,%d\n", i, i+3);
        return rc;
    }

/* Single flip, flip one arc and assume it works.
Call it a red arc (or a red blue arc if you prefer), and say it is band 0.
Fine, but what if this chains around to another red arc?
Let j be the first red arc, travelling clockwise, that is chained to 0.
If j is 2, then I need to flip 1.
If j is -2, then I need to flip -1.
These single flips are efficiently checked by the mask m,
and that's the first thing we do.
To illustrate say j is 12.
1 connects by a yello chain to 11.
If it didn't then 12 would not be the first arc connected to 0.
This yellow chain holds the red chain away from arcs 2 4 6 8 10.
The yellow chain could connect to some of the yellow arcs inside, such as 7.
Or it might not.
Or it might connect to all of them.
We must guard against this last possibility.
We need to flip all the yellow arcs beneath this red chain.
Call this set of arcs S.
In this case 1 3 5 7 9 11.
If the yellow chain doesn't connect to all the arcs in S, then maybe we don't
have to flip all of them, but we might have to flip all of them,
and we can flip all of them, so that is the test.
Flip the set S, for every odd j, as we march around.
We don't have to test j = 1, we already verified that flip.
We don't have to go up to j = -1, as band 0 connecting to itself is trivial.
We don't have to consider j = -3.
S is then the complement of -1, and we already verified that flip.
So that is the algorithm. */

    if(yescount >= 3) {
        if(debug) {
            printf("%d bands %d%d %02x ", nbands, c1, c2, m);
            printBorder(cp, 0);
        }
        for(start = 0; start < nbands; ++start) {
            if(!(m&(1<<start))) continue;
            start1 = start + 1;
            if(start1 == nbands) start1 = 0;
            if(!(m&(1<<start1))) continue;
            start_1 = start - 1;
            if(start_1 < 0) start_1 += nbands;
            if(!(m&(1<<start_1))) continue;
            start3 = start + 3; // next band we might need to flip
            if(start3 >= nbands) start3 -= nbands;
            start_3 = start - 3;
            if(start_3 < 0) start_3 += nbands;
            cpRestore();
            swapBand(start1); // we already confirmed this flip
            for(j = start3; j != start_3; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_single;
            }
            if(debug) printf("single,%d\n", start);
            return 1;
next_single: ;
        }
    }

/* flipping two adjacent, like 0 and 1, has all the conditions of flipping 0,
and 1 but that forces an individual flip of 0, so covered by single above.
Double is flipping two successive red arcs, such as bands 0 and 2.
Let j be the first red arc, travelling clockwise, that is chained to 0 or 2.
Say j is 12.
In the first case, 2 chains to 12.
The set S is now 3 5 7 9 11.
We might have to flip all of these as one.
We might not have to, but we can, so that is the test.
Next case: 2 doesn't chain to 12, so 0 must.
The set T is now 1 3 5 7 9 11, 1 more than S.
We might have to flip all of these as one.
We might not have to, but we can, so that is the test.
Both S and T must satisfy, as j marches around.
Start by flipping 3, or 1 and 3.
We can test for the individual flip of 3, by the mask, and we should,
but still we have to start with 3 so we can test 3 and 1 together.
And we have to go all the way around to -3.
Here T is 1 through -3, and that is the complement of -1,
and we check for the individual flip of -1, but still we go all the way up
to -3, because the set S is 3 through -3.
That is the algorithm for double.
triple is double while flipping the arc inside, and we'll get to that.
triple+, double with a single flip next to it,
has all the conditions of that single flip, and the double forces the
single flip to happen on its own, so covered by the single case.
Double double, like flipping 0 2 3 and 5, has all the conditions of flipping just 0 and 2,
and the second double forces a flip of 0 and 2. Covered by double below.
Four in a row is again two doubles, intertwined.
We have all the conditions of the first double, and the second double
says the first double must happen as well,
so covered by the double case below. */

    if(yescount >= 2) {
        for(start = 0; start < nbands; ++start) {
            start3 = start + 3; // next band we might need to flip
            if(start3 >= nbands) start3 -= nbands;
            if(!(m&(1<<start3))) continue;
            start_1 = start - 1;
            if(start_1 < 0) start_1 += nbands;
            if(!(m&(1<<start_1))) continue;
            start1 = start + 1;
            if(start1 >= nbands) start1 -= nbands;
            start2 = start + 2;
            if(start2 >= nbands) start2 -= nbands;
// if 8 bands, then flipping 0 and 2 is the same as flipping 4 and 6.
// However the conditions around it are not the same.
            if(start < 4 || nbands > 8) {
                cpRestore();
                swapBand(start);
                swapBand(start2);
                if(!equivalentColorable()) goto next_double;
            }
            cpRestore();
            for(j = start3; j != start_1; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_double;
// switch between S and T
                swapBand(start1);
                if(!equivalentColorable()) goto next_double;
            }
            if(debug) {
                if(yescount == 2) {
                    printf("%d bands %d%d %02x ", nbands, c1, c2, m);
                    printBorder(cp, 0);
                }
                printf("double,%d,%d\n", start, start2);
            }
            return 1;
next_double: ;
        }
    }

    if(yescount >= 4) {
        for(start = 0; start < nbands; ++start) {
            start1 = start + 1;
            if(start1 == nbands) start1 = 0;
            if(!(m&(1<<start1))) continue;
            start_1 = start - 1;
            if(start_1 < 0) start_1 += nbands;
            if(!(m&(1<<start_1))) continue;
            start2 = start + 2;
            if(start2 >= nbands) start2 -= nbands;
            if(!(m&(1<<start2))) continue;
            start4 = start + 4;
            if(start4 >= nbands) start4 -= nbands;
            if(!(m&(1<<start4))) continue;
            start3 = start + 3;
            if(start3 >= nbands) start3 -= nbands;
            cpRestore();
            swapBand(start);
            swapBand(start3);
            if(!equivalentColorable()) goto next_pair;
            start_3 = start - 3;
            if(start_3 < 0) start_3 += nbands;
            cpRestore();
            swapBand(start1); // we already confirmed this flip
            for(j = start3; j != start_3; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_pair;
            }
            cpRestore();
            start_2 = start + 6;
            if(start_2 >= nbands) start_2 -= nbands;
            swapBand(start4); // we already confirmed this flip
            for(j = start_2; j != start; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_pair;
            }
            if(debug) printf("pair,%d,%d\n", start, start3);
            return 1;
next_pair: ;
        }
        
// Flip bands 0 1 and 2 together. red yellow red.
// This is the combination of double, and single shifted by 1.
        for(start = 0; start < nbands; ++start) {
            if(!(m&(1<<start))) continue;
            start_1 = start - 1;
            if(start_1 < 0) start_1 += nbands;
            if(!(m&(1<<start_1))) continue;
            start2 = start + 2;
            if(start2 >= nbands) start2 -= nbands;
            if(!(m&(1<<start2))) continue;
            start3 = start + 3;
            if(start3 >= nbands) start3 -= nbands;
            if(!(m&(1<<start3))) continue;
            start1 = start + 1;
            if(start1 >= nbands) start1 -= nbands;
            cpRestore();
            swapBand(start);
            swapBand(start1);
            swapBand(start2);
            if(!equivalentColorable()) goto next_triple;
            cpRestore();
            for(j = start3; j != start_1; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_triple;
// switch between S and T
                swapBand(start1);
                if(!equivalentColorable()) goto next_triple;
            }
            start_2 = start - 2;
            if(start_2 < 0) start_2 += nbands;
            start4 = start + 4;
            if(start4 >= nbands) start4 -= nbands;
            cpRestore();
            swapBand(start2);
            for(j = start4; j != start_2; j = (j + 2) % nbands) {
                swapBand(j);
                if(!equivalentColorable()) goto next_triple;
            }
            if(debug) printf("triple,%d,%d\n", start, start2);
            return 1;
next_triple: ;
        }
    }

// Test the diameter across 8 and 10 bands.

    if(nbands == 8) {
        if((m&0xaa) == 0xaa) {
            cpRestore();
            swapBand(0);
            swapBand(4);
            if(equivalentColorable()) {
                if(debug) printf("across,%d,%d\n", 0, 4);
                return 1;
            }
        }
        if((m&0x55) == 0x55) {
            cpRestore();
            swapBand(1);
            swapBand(5);
            if(equivalentColorable()) {
                if(debug) printf("across,%d,%d\n", 1, 5);
                return 1;
            }
        }

// flip 0 2 and 5, but that's the same as 4 5 and 6 which is a triple.
    }

    if(nbands == 10 && yescount >= 4) {
        for(start = 0; start < halfband; ++start) {
            static const int masks[] = { 0x252, 0x0a5, 0x14a, 0x294, 0x129};
            j = masks[start];
            if((m&j) != j) continue;
            start1 = start + 1;
            if(start1 >= nbands) start1 -= nbands;
            start2 = start + 3;
            if(start2 >= nbands) start2 -= nbands;
            cpRestore();
            swapBand(start1);
            swapBand(start2);
            if(!equivalentColorable()) continue;
            start1 = start + 2;
            if(start1 >= nbands) start1 -= nbands;
            start2 = start + 4;
            if(start2 >= nbands) start2 -= nbands;
            cpRestore();
            swapBand(start1);
            swapBand(start2);
            if(!equivalentColorable()) continue;
            start1 = start + 6;
            if(start1 >= nbands) start1 -= nbands;
            start2 = start + 8;
            if(start2 >= nbands) start2 -= nbands;
            cpRestore();
            swapBand(start1);
            swapBand(start2);
            if(!equivalentColorable()) continue;
            start1 = start + 7;
            if(start1 >= nbands) start1 -= nbands;
            start2 = start + 9;
            if(start2 >= nbands) start2 -= nbands;
            cpRestore();
            swapBand(start1);
            swapBand(start2);
            if(!equivalentColorable()) continue;
            if(debug) printf("across,%d,%d\n", start, start + 5);
            return 1;
        }
    }

    return 0;
}

#undef cpRestore

static int chainColorable1(void)
{
    c1 = 1, c2 = 2, c3 = 3, c4 = 4;
    if(chainColorable2()) return 1;
    c1 = 1, c2 = 3, c3 = 2, c4 = 4;
    if(chainColorable2()) return 1;
    c1 = 1, c2 = 4, c3 = 2, c4 = 3;
    return chainColorable2();
}

// number of connections for sewing, and number of lines for triangulation
static int nsew, nlines;

// indicate sewing with = and line with -
// 3=5 sews 3 and 5 together, 3-5 is a line from 3 to 5
static void printLines(const char *msg, const uchar * a, const uchar * b)
{
    printf("%s", msg);
    for(int j = 0; j < nsew + nlines; ++j)
        printf(" %d%c%d", a[j], (j < nsew ? '=' : '-'), b[j]);
    printf("\n");
}

struct hole {
    uchar cycle[MAXBORDER];
    int clen; // cycle length
};
static struct hole holes[MAXBORDER];
static int nholes;

/* print the cycle length around each hole, then the number of points
in the hole. 5p1 means we had an empty pentagon after sewing and drawing,
and we put one point in it, and that point is of course connected
to all 5 vertices of said pentagon.
Earlier versions might put 2 3 or 4 points in a hole, but that is deprecated.
Thus we always print p1. */
static void printHoles(int details)
{
    printf("holes");
    for(int j=0; j<nholes; ++j) {
        struct hole *h  = holes + j;
        printf(" %d", h->clen);
        if(!details) continue;
        printf("p1");
    }
    printf("\n");
    if(details)
        printf("replace %d points with %d\n", ninternal + nsew, nholes);
}

/* This is recursive.
The first three parameters are always the connections through the border.
If a cycle has a line through it, cut it in two and see if
those two pieces are holes. At start, cycle[j] = j, and cycle length
is nborder, so the cycle is the border of H. */
static void findHoles(const uchar * a, const uchar * b, int top, const uchar * cycle, int clen)
{
    int i, j, aloc, bloc;
    uchar newcycle[MAXBORDER];
    uchar rm_a, rm_b; // should we remove points a or b?
    struct hole *h;

// a triangle is not a hole
    if(clen <= 3) return;

// look for an edge or sewing inside our cycle
    for(i = 0; i < top; ++i) {
// a[i]-b[i] might be the edge that partitions our cycle.
        aloc = bloc = -1;
        rm_a = rm_b = 0;
        for(j = 0; j < clen; ++j) {
            if(cycle[j] == a[i]) aloc = j;
            if(cycle[j] == b[i]) {
                bloc = j;
                if(i < nsew) rm_b = 1;
            }
        }
        if(aloc < 0 || bloc < 0) continue;
// this edge has both points on our cycle
// put a before b in the seequence of our cycle
        if(bloc < aloc) {
            j = aloc, aloc = bloc, bloc = j;
            if(rm_b) rm_a = 1, rm_b = 0;
        }
// this edge could be part of our cycle, travelling around the cycle,
// not through it.
        if(bloc == aloc + 1) continue;
        if(aloc == 0 && bloc == clen - 1) continue;
        goto edge; // it's a real edge running through
    }

// no edge running through
    h = holes + nholes;
    memcpy(h->cycle, cycle, clen);
    h->clen = clen;
    ++nholes;
    return;

edge:
/* If sewing, we are keeping the point that originally came from a, and removing
the point that originally came from b. When sewing is established,
and 3 sews to 5, then the composite point (3,5) sews to 7,
it should be listed as 3=7.
That way we will see it, because we keep 3 in the cycle and remove 5. */
    findHoles(a, b, top,
    cycle + (aloc+rm_a), bloc-rm_b - (aloc+rm_a) + 1);
// build the second cycle using our local array.
    aloc -= rm_a; // could be -1
    bloc += rm_b; // could be clen
    memcpy(newcycle, cycle + bloc, clen - bloc);
    memcpy(newcycle + clen - bloc, cycle, aloc + 1);
    findHoles(a, b, top,
    newcycle, aloc + 1 + clen - bloc);
}

// return 0 means these holes with these points and connections are not compatible
// with the color pattern and given rotation.
// That's a good thing though; these holes are precluding some bad patterns.
static int holeColor(const uchar *a, const uchar *b, int cpr)
{
    const struct hole *h = holes;
    for(int i=0; i < nholes; ++i, ++h) {
        const uchar *cycle = h->cycle;
        uchar used = 0;
        for(int j = 0; j < h->clen; ++j)
            used |= 1 << cp[rots[cpr][cycle[j]]];
// ok iff less than 4 colors used, all incident to the injected point p
        if(used == 0x1e) return 0;
    }
    return 1;
}

// Return 1 if this set of sewing and lines and holes allows G to be colored.
static int checkLines(const uchar * a, const uchar * b)
{
    int i, j, cpr;
    const int top = nsew + nlines; // number of connections made in the border
// we are removing the subgraph h and points sewn together
    const int h_size = ninternal + nsew;
    uchar cycle[MAXBORDER];
    struct hole *h;

    if(debug) printLines("lines", a, b);

    nholes = 0;
    for(j = 0; j < nborder; ++j)
        cycle[j] = j;
    findHoles(a, b, top, cycle, nborder);
// holes are now creeated, if there are any.
    if(debug) printHoles(0);

// Squares should be sewn or triangulated
    for(j=0; j<nholes; ++j)
        if(holes[j].clen == 4) return 0;

    for(i = 0; i < npattern; ++i) {
        if(colorable[i]) continue;
// now it's a bad (uncolorable) pattern.
        cp = patterns + i * nborder;

/*********************************************************************
Warning! If we have to use lines to complete the validation of a subgraph H,
wherein H cannot be part of the smallest uncolorable graph G,
then we might not be able to take advantage of the rotations
and reflections of H, that is to say, the symmetries of H.
These symmetries are described in the first line of the input file.
Here is a thought experiment to illustrate.
Say the border is 12 points arranged in a vertical tube.
0 is at the top, 6 is at the bottom, 1 through 5 go down the right side,
7 through 11 come up the left side.
H has a symmetry of reflection.
We could use ^ in the first line to indicate this.
It makes the program run faster.
But then we see the proof uses a line drawn from 1 down and across to 9.
This discounts  any bad color patterns where 1 and 9 would be given the same color.
All the bad color patterns are precluded and we think we're in good shape.
But this color pattern is a canonical representative
of an equivalence class of color patterns.
In this representative, 1 and 9 have the same color, but 3 and 11 do not.
There is another bad pattern, represented by its reflection,
wherein 3 and 11 have the same color, and 1 and 9 do not.
To be safe, we need to test this configuration of lines and holes
against all bad patterns, all the members of the equivalence class,
all the rotations. Thus the loop over rotations.
*********************************************************************/

        for(cpr = 0; cpr < nrots; ++cpr) {
            for(j = 0; j < top; ++j) {
/* If sewing points together, j < nsew, then those points have to have
the same color. If a line is drawn between points, then those points
have to have different colores. The exclusive or operator accomplishes this. */
                if((j < nsew) ^ (cp[rots[cpr][a[j]]] == cp[rots[cpr][b[j]]])) {
// this rotation of this bad color pattern is mismatched.
// That's good. Go on to the next rotation.
                    goto nextrotation;
                }
            }

            if(nholes) {
/* There might still be a way to preclude this pattern, by putting points
in holes. holeColor() return 0 is a good thing - it means the points
in the holes preclude this rotation of this color pattern. */
                if(!holeColor(a, b, cpr)) goto nextrotation;
                if(debug) {
                    printf("subcrash ");
                    printBorder(cp, cpr);
                }
                return 0;
            }

// no holes, this pattern is not precluded by these lines,
// and it remains uncolorable.
            if(debug) {
                printf("crash ");
                printBorder(cp, cpr);
            }
            return 0;

nextrotation:;
        }
    }

// this pattern of lines and holes and points does the trick!
// As long as the new graph is smaller than the original.
    if(nholes < h_size) return 1;
    printLines("maybe lines", a, b);
    printHoles(1);
    return 0;
}

// return 1 if the newest line crosses an earlier line.
static int crossLines(uchar * a, uchar * b, int top)
{
    uchar s, t, u, v;
    u = a[top], v = b[top];
    if(v <= u) eprint("backward line at depth %d", top);
    for(int j = 0; j < top; ++j) {
        s = a[j], t = b[j];
        if(s == u) {
            if(t == v) return 1; // duplicate line
            continue;
        }
        if(t == v) continue;
        if((s > u && s < v) ^ (t > u && t < v))
            return 1;
    }
    return 0;
}

// return 1 if graph becomes colorable using sewing and lines etc.
static int drawLines(void)
{
// connect a[i] to b[i]
    uchar a[MAXBORDER], b[MAXBORDER];
    int sp = -1; // stack pointer
    int k, sewtop;

/* sewtop is the number of sewing connections that must be made in the border.
It loops from 0 up to (but not including) nborder/2.
In a hexagon, nborder = 6, we can sew 0 pairs of points together, 1 pair,
or 2 pair. This function won't return success unless nsew, the number of
sewings, equals sewtop. The rest is filled in with lines for triangulation,
or sometimes by injected points.
A push pop stack sets the sewing connections first, then lines,
then fills in any holes with points if that makes sense.
First time through the loop, sewtop is 0, there is no sewing,
all connections are lines drawn, then holes can be filled with points.
After that, sewing must take place.
sp == sewtop is a transition, when the number of sewing
pushed onto the stack equals the number of sewing expected.
Next connection pushed onto the stack will be a line drawn.
nsew == sewtop is another transition, when we have enough sewing to test
the arrangement against the uncolorable patterns and seeif we have
precluded all of them. */

    nsew = 0, nlines = 0;

    for(sewtop = 0; sewtop < nborder / 2; ++sewtop) {
        if(debug) printf("sewtop %d\n", sewtop);

push:
        ++sp;
        if(nsew == sewtop && checkLines(a, b)) {
            printLines("ok lines", a, b);
            printHoles(1);
            return 1;
        }

// connect 0 to 1, which is impossible, but next will step us through
        a[sp] = 0, b[sp] = 1;
// We have to be past the last line or sew that we made.
// But not if we are transitioning from sewing to lines.
// Copying the previous connection is impossible, but next will step us through.
        if(sp && sp != sewtop)
            a[sp] = a[sp - 1], b[sp] = b[sp - 1];

next:
// connect or sew a to the next b
        if(++b[sp] >= nborder) {
            if(++a[sp] >= nborder) goto pop;
            b[sp] = a[sp] + 1;
            goto next;
        }

// the other side of the cycle
        if(a[sp] == 0 && b[sp] == nborder - 1) goto next;

        if(crossLines(a, b, sp)) goto next;

/* If 3 and 5 sew together, and we want a connection from (3,5) to 7,
then 3-7 and 5-7 are semantically the same.
I don't want to do things twice.
Each new line must refer to the first point of a sewn pair. */
        if(sp && sp < sewtop) {
            for(k = 0; k < sp; ++k) {
                if(b[k] == a[sp]) goto next;
                if(b[k] == b[sp]) goto next;
            }
// we can't sew 3 to 7, and then 3 to 8, that squashes 7 and 8 and those are
// adjacent countries with different colors.
            if(a[sp] == a[sp - 1] && b[sp] == b[sp - 1] + 1) goto next;
        }

        if(sewtop && sp >= sewtop) {
            for(k = 0; k < sewtop; ++k) {
                if(b[k] == a[sp]) goto next;
                if(b[k] == b[sp]) goto next;
                if(a[k] == a[sp] && b[k] == b[sp] + 1) goto next;
                if(a[k] == a[sp] && b[k] == b[sp] - 1) goto next;
                if(a[sp] == 0 && b[sp] == a[k] && b[k] == nborder - 1) goto next;
            }
        }

        if(sp < sewtop) ++nsew;
        else ++nlines;
        goto push;

pop:
        if(--sp >= 0) {
            if(nlines) --nlines;
            else --nsew;
            goto next;
        }

        if(nlines || nsew)
            eprint("counts do not return to 0 after sewtop %d", sewtop);
    }

    return 0;
}

int main(int argc, char **argv)
{
    int i, change;
    int colorCount;

    ++argv, --argc;

    if(argc && !strcmp(argv[0], "-d")) {
        debug = 1;
        ++argv, --argc;
    }

    if(argc == 0)
        eprint("usage:  4ct [-d] graph_file(s)", 0);

top:
    npattern = nborder = ninternal = nrots = nperim = nedges = 0;
    colorCount = 0;
    puts(argv[0]);
    readGraph(argv[0]);
    buildPatterns();
    colorable = emalloc(npattern);
    memset(colorable, 0, npattern);

    for(i = 0; i < npattern; ++i) {
        cp = patterns + i * nborder;
        if(colorInternal(cp))
            colorable[i] = 1, ++colorCount;
    }
    printf("%d patterns directly colorable\n", colorCount);
    if(colorCount == npattern) {
        puts("ok");
        goto nextfile;
    }

    goodBad();

    while(1) {
        change = 0;
        for(i = 0; i < npattern; ++i) {
            if(colorable[i]) continue;
            cp = patterns + i * nborder;
            if(!chainColorable1()) continue;
            colorable[i] = 1;
            ++colorCount;
            ++change;
            if(!debug) continue;
            printf("swap %d%d ", c1, c2);
            printBorder(cp, 0);
        }
        if(!change) break;
        printf("%d colorable\n", change);
        if(colorCount < npattern) continue;
        puts("ok");
        goto nextfile;
    }

    printf("unknown %d%%\n", (npattern - colorCount) * 100 / npattern);
    goodBad();

    if(drawLines()) goto nextfile;

    return 1;

nextfile:
    free(colorable);
    free(patterns);
    ++argv, --argc;
    if(argc) goto top;

    return 0;
}
