// Copyright (C) 2014-2015 Mark Owen.
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

// http://www.quinapalus.com

// To build and run:
// sudo apt-get install picosat
// gcc unl-ng.c -l picosat
// ./a.out 2
// where "2" is mode selection. Mode "0" guarantees to find a solution if there is one; modes
// "1" and "2" may be faster but may fail on feasible problems.
// If you have >=3 cores, you can try running the program simultaneously in all three modes
// ./a.out 0 &
// ./a.out 1 &
// ./a.out 2 &
// and see which finishes first.

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "/usr/include/picosat/picosat.h"

#define X 20 // width of target pattern
#define Y 5  // height of target pattern
#define G 3  // number of generations to go back

// array specifying the desired result pattern
int pat[Y][X]={
{1,0,0,0,1,0,0,1,1,0,0,1,1,1,0,0,1,0,0,1},
{1,1,0,1,1,0,1,0,0,1,0,1,0,0,1,0,1,0,1,0},
{1,0,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,0},
{1,0,0,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0},
{1,0,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1},
};


#define XYO (G*2+1)    // extra border in X and Y
#define XX (X+XYO*2)   // internal width and height
#define YY (Y+XYO*2)
#define GG (G+1)       // total generations (including first and last)

#define T(x,y,g) (1+(x)+(y)*XX+(g)*XX*YY) // index of Boolean variable corresponding to state of cell (x,y) at generation g

int out[GG][YY][XX];   // state at each generation (for presenting results only)

int bitcnt[512];       // bitcnt[x]==number of bits set in x
int res[512];          // output of Life rule given 3x3 cells in previous generation as a bitmap

int main(int argc,char**argv) {
  int dx,dy,g,k,m,n,u,x,y;
  int mode;
  PicoSAT*ps;

  mode=2;
  if(argc>1) mode=atoi(argv[1]); // default to mode 2

  bitcnt[0]=0;
  for(m=0;m<512;m+=2) bitcnt[m]=bitcnt[m/2],bitcnt[m+1]=bitcnt[m]+1; // set up bit count array
  for(m=0;m<512;m++) { // set up Life rules
    n=bitcnt[m&0x1ef]; // neighbour count
    k=(m>>4)&1;        // central cell alive?
    if(n==3) k=1;      // cell birth
    if(n<2||n>3) k=0;  // cell death
    res[m]=k;
    }
  ps=picosat_init(); assert(ps);

  // enforce pattern at generation 0
  for(x=0;x<XX;x++) for(y=0;y<YY;y++) {
    u=T(x,y,0);
    if(x<XYO||x>=XX-XYO||y<XYO||y>=YY-XYO||pat[y-XYO][x-XYO]==0) picosat_add(ps,-u); // force blank border
    else picosat_add(ps,u);
    picosat_add(ps,0);
    }

  // force blank borders of appropriate width at each generation
  for(g=1;g<GG;g++) {
    switch(mode) {
case 0: m=g+1; break;   // maximum possible freedom
case 1: m=XYO-1; break; // keep all generations within 1 cell of final pattern
case 2: m=XYO-g; break; // disallow production of spurious live cells outside light cone
default: assert(0);
      }
    for(x=0;x<XX;x++) for(y=0;y<YY;y++) {
      u=T(x,y,g);
      if(x<m||x>=XX-m||y<m||y>=YY-m) { picosat_add(ps,-u); picosat_add(ps,0); }
      }
    }

  // add Life rules for all cells at all generations; let PicoSAT sort out redundant constraints
  for(g=0;g<G;g++)
    for(y=1;y<YY-1;y++)
      for(x=1;x<XX-1;x++)
        for(m=0;m<512;m++) { // all possible bitmaps of neighbours in previous generation
          u=1;               // bit mask of cell in previous generation
          for(dy=-1;dy<2;dy++) for(dx=-1;dx<2;dx++) { // loop over all cells in 3x3 area
            picosat_add(ps,T(x+dx,y+dy,g+1)*((m&u)?-1:1));
            u+=u; // shift mask
            }
          picosat_add(ps,T(x,y,g)*(res[m]?1:-1)); // implied result
          picosat_add(ps,0);
          }

  u=picosat_sat(ps,-1); // run solver

  if(u==PICOSAT_SATISFIABLE) { // found a solution: extract results from PicoSAT's internal representation
    for(g=0;g<GG;g++) for(y=0;y<YY;y++) for(x=0;x<XX;x++) out[g][y][x]=(picosat_deref(ps,T(x,y,g))==1)?1:0; 

    // output all generations
    fprintf(stderr,"Generation %d\n",-G);
    for(y=1;y<YY-1;y++) {
      for(x=1;x<XX-1;x++) fprintf(stderr,"%c ",out[G][y][x]?'#':'.');
      fprintf(stderr,"\n");
      }

    // check the result
    m=0;
    for(g=GG-1;g>0;g--) {
      fprintf(stderr,"Generation %d\n",1-g);
      for(y=1;y<YY-1;y++) {
        for(x=1;x<XX-1;x++) {
          k=out[g][y][x];
          n=-k; for(dy=-1;dy<2;dy++) for(dx=-1;dx<2;dx++) n+=out[g][y+dy][x+dx];
          if(n==3) k=1;
          if(n<2||n>3) k=0;
          fprintf(stderr,"%c ",k?'#':'.'); // calculated result from previous generation
          if(k!=out[g-1][y][x]) m=1; // error? set flag
          }
        fprintf(stderr,"\n");
        }
      if(!m) fprintf(stderr,"Verified OK\n"); else fprintf(stderr,"Verify failed\n");
      }
    fflush(stderr);

    // output in GtkLife format
    printf("#GLF 1.0\nx = %d, y = %d, width = %d, height = %d\n\n",-XX/2,-YY/2,XX,YY);
    for(y=0;y<YY;y++) {
      for(x=0;x<XX;x++) printf("%c",out[G][y][x]?'o':'b');
      printf("$\n");
      }
    printf("\n");
    }

  else fprintf(stderr,"Unsatisfiable\n");
  picosat_reset(ps);
  return 0;
  }
