// How to cope with fractional tile weights?
// add a weighted tile add, which adds a tile to a square.
// Eventually fade in the square behind the tile according to
// the sum of all tiles added to this square. Background tiles
// will have to be drawn after all others.
//
// Start with greyscape map and build up b/w features, then merge in
// colours for all white cells at end.

/*
      if (c=='.')
	puttile(imgbuf,sq1_bits,tx,ty,grey1,grey2,boardxsize,boardysize);
      else if (c=='-')
	puttile(imgbuf,sq2_bits,tx,ty,blue2,grey2,boardxsize,boardysize);
      else if (c=='=')
	puttile(imgbuf,sq3_bits,tx,ty,blue1,grey2,boardxsize,boardysize);
      else if (c=='+')
	puttile(imgbuf,sq2_bits,tx,ty,red2 ,grey2,boardxsize,boardysize);
      else if (c=='#')
	puttile(imgbuf,sq3_bits,tx,ty,red1 ,grey2,boardxsize,boardysize);
      else
*/

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define PNG_INTERNAL
#include <png.h>


#define max(a,b)        ((a>b)?a:b)
#define min(a,b)        ((a<b)?a:b)

#include "biglet.h"
#include "bigbln.h"
#include "bigsqr.h"
#include "numbers.h"
#include "blankgame.xbm"

#define tilesize 24
#define edgeoffset tilesize/2
#define rackoffset tilesize/8
#define boardxsize (tilesize*15+edgeoffset*2)
#define boardysize (tilesize*16+edgeoffset*2+rackoffset*2)

#define MAXSIZE    boardxsize*boardysize
#define MAXCOLORS  256

static char outname[1024];

main(argc,argv)
     int argc;
     char **argv;
{
  FILE *file;
  char board[15][15],rack[7],c;
  int boardwt[15][15];
  int i,j,k,x,y,z,tx,ty,wt,score,tiles;
  unsigned char bw[MAXSIZE];
  int black=0,grey1=1,grey2=2,red1=3,red2=4,blue1=5,blue2=6,white=7;
  int imgbuf[MAXSIZE];
  int rmap[MAXCOLORS]={0,255,255,160,255,  0,160,255};
  int gmap[MAXCOLORS]={0,200,255,  0,120,  0,160,255};
  int bmap[MAXCOLORS]={0,100,160,  0,120,180,255,255};
  png_byte  image[MAXSIZE];
  png_color palette[MAXCOLORS];

  //for (i=0;i<64;i++) rmap[i+64]=gmap[i+64]=bmap[i+64]=i;
  for (i=0;i<256;i++) rmap[i]=gmap[i]=bmap[i]=i;

  if (argc == 2) {
    file=fopen(argv[1],"r");
    if (file == NULL) {
      fprintf(stderr, "wsc_png: cannot open %s\n", argv[1]);
      exit(1);
    }
    strcpy(outname, "wsc_board.png");
  } else if (argc == 3) {
    file=fopen(argv[1],"r");
    if (file == NULL) {
      fprintf(stderr, "wsc_png: cannot open %s\n", argv[1]);
      exit(1);
    }
    strcpy(outname, argv[2]);
  } else if (argc == 1) {
    file=fopen("wsc_board.dat","r");
    if (file == NULL) {
      fprintf(stderr, "wsc_png: cannot open default wsc_board.dat (wrong directory or permissions?)\n");
      exit(1);
    }
    strcpy(outname, "wsc_board.png");
  } else {
    fprintf(stderr, "syntax: wsc_png boardfile.dat?\n");
    exit(1);
  }


/* read starting board layout */
  for (i=0;i<15;i++)
    fscanf(file," %15c ",board[i]);
  fscanf(file," %7c %d %d\n",rack,&score,&tiles);  // rack
  fscanf(file,"%*[^\n]\n"); // ignore next line


/* clear board */
  for (x=0;x<boardxsize;x++)
    for (y=0;y<boardysize;y++) {
      i=x+boardxsize*(boardysize-y-1);
      j=i/8;
      k=i%8;
      if (blankgame_bits[j]>>k&1==1) imgbuf[x*boardysize+y]=255;
      else                           imgbuf[x*boardysize+y]=0;
    }

/* add starting tile layout */
  for (x=0;x<15;x++)
    for (y=0;y<15;y++) {
      c=board[14-y][x];
      tx=tilesize*x+edgeoffset;
      ty=tilesize*y+edgeoffset+tilesize+2*rackoffset;
      if (islower(c))      putftile(imgbuf,lblanks_bit[(int)c-'a'],tx,ty,
				    boardxsize,boardysize,255);
      else if (isupper(c)) putftile(imgbuf,letters_bit[(int)c-'A'],tx,ty,
				    boardxsize,boardysize,255);
      if (islower(c)||isupper(c)) boardwt[x][y]=256;
    }


/* add potential tiles */
  while (fscanf(file,"%c,%i,%i,%i\n",&c,&x,&y,&wt)!=EOF) {
    tx=tilesize*x+edgeoffset;
    ty=tilesize*y+edgeoffset+tilesize+2*rackoffset;
    if (islower(c))      putftile(imgbuf,lblanks_bit[(int)c-'a'],tx,ty,
				  boardxsize,boardysize,wt);
    else if (isupper(c)) putftile(imgbuf,letters_bit[(int)c-'A'],tx,ty,
				  boardxsize,boardysize,wt);
    boardwt[x][y]+=wt;
  }


  for (x=0;x<4;x++) {
    i=score%10; j=tiles%10;
    tx=366-5*x;
    if (score>0) putnum(imgbuf,numbers_bit[i],tx,17,black,white,
                        boardxsize,boardysize);
    if (tiles>0) putnum(imgbuf,numbers_bit[j],tx,5,black,white,
                        boardxsize,boardysize);
    score/=10; tiles/=10;
  }


/* write board */
  for (i=0;i<MAXCOLORS;i++) {
    palette[i].red  =(png_byte)rmap[i];
    palette[i].green=(png_byte)gmap[i];
    palette[i].blue =(png_byte)bmap[i];
  }
  for (y=0;y<boardysize;y++)
    for (x=0;x<boardxsize;x++)
      image[x+boardxsize*y]=(png_byte)imgbuf[x*boardysize-y+boardysize-1];

  write_png(outname,image,palette,boardxsize,boardysize);

}


putftile(img,tile,x,y,xsize,ysize,wt)
     int *img,x,y,xsize,ysize,wt;
     unsigned int tile[tilesize];
{
  int dx,dy,z;
  unsigned int mask;

  for (dy=0;dy<tilesize;dy++) {
    mask=tile[tilesize-dy-1];
    for (dx=0;dx<tilesize;dx++) {
      if (mask&1) img[(x+dx)*ysize+y+dy]+=wt;
      mask=mask/2;
    }
  }

}


puttile(img,tile,x,y,fg,bg,xsize,ysize)
     int *img,x,y,fg,bg,xsize,ysize;
     unsigned int tile[tilesize];
{
  int dx,dy,z;
  unsigned int mask;

  for (dy=0;dy<tilesize;dy++) {
    mask=tile[tilesize-dy-1];
    for (dx=0;dx<tilesize;dx++) {
      if (mask&1)
	img[(x+dx)*ysize+y+dy]=fg;
      else
	img[(x+dx)*ysize+y+dy]=bg;
      mask=mask/2;
    }
  }

}


putnum(img,num,x,y,fg,bg,xsize,ysize)
     int *img,x,y,fg,bg,xsize,ysize;
     unsigned char num[7];
{
  int dx,dy,z;
  unsigned int mask;

  for (dy=0;dy<7;dy++) {
    mask=num[6-dy];
    for (dx=0;dx<5;dx++) {
      if (mask&1) img[(x+dx)*ysize+y+dy]=fg;
      mask=mask/2;
    }
  }
}



/* write a png file */
write_png(file_name, image, palette, x, y)
     char *file_name;
     png_byte  *image;
     png_color *palette;
     int x,y;
{
   FILE *fp;
   png_structp png_ptr;
   png_infop info_ptr;
   png_uint_32 k, height, width;
   png_bytep row_pointers[1000];

   width=(png_uint_32)x;
   height=(png_uint_32)y;

   /* open the file */
   fp = fopen(file_name, "wb");
   if (fp == NULL)
      return;

   /* Create and initialize the png_struct with the desired error handler
    * functions.  If you want to use the default stderr and longjump method,
    * you can supply NULL for the last three parameters.  We also check that
    * the library version is compatible with the one used at compile time,
    * in case we are using dynamically linked libraries.  REQUIRED.
    */
   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
      (png_voidp)NULL, (png_error_ptr)NULL, (png_error_ptr)NULL);

   if (png_ptr == NULL)
   {
      fclose(fp);
      return;
   }

   /* Allocate/initialize the image information data.  REQUIRED */
   info_ptr = png_create_info_struct(png_ptr);
   if (info_ptr == NULL)
   {
      fclose(fp);
      png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
      return;
   }

   /* Set error handling.  REQUIRED if you aren't supplying your own
    * error hadnling functions in the png_create_write_struct() call.
    */
   if (setjmp(png_ptr->jmpbuf))
   {
      /* If we get here, we had a problem reading the file */
      fclose(fp);
      png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
      return;
   }

   /* set up the output control if you are using standard C streams */
   png_init_io(png_ptr, fp);

   /* try to optimise compression */
   png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
   png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);

   /* Set the image information here.  Width and height are up to 2^31,
    * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
    * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
    * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
    * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
    * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
    * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
    */

   png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_PALETTE,
      PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

   /* ... set palette colors ... */
   png_set_PLTE(png_ptr, info_ptr, palette, MAXCOLORS);

   /* Write the file header information.  REQUIRED */
   png_write_info(png_ptr, info_ptr);

   /* The easiest way to write the image (you may have a different memory
    * layout, however, so choose what fits your needs best).  You need to
    * use the first method if you aren't handling interlacing yourself.
    */
   for (k = 0; k < height; k++)
     row_pointers[k] = image + k*width;

   /* One of the following output methods is REQUIRED */
   png_write_image(png_ptr, row_pointers);

   /* It is REQUIRED to call this to finish writing the rest of the file */
   png_write_end(png_ptr, info_ptr);

   /* clean up after the write, and free any memory allocated */
   png_destroy_write_struct(&png_ptr, &info_ptr);

   /* close the file */
   fclose(fp);

   /* that's it */
   return;
}
