#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#include "giflib.h"
#include "myerror.h"

jmp_buf jmpbuffer;

void main (int argc, char *argv[]) {
  FILE *fpin, *fpout;
  unsigned char buf[BUFSIZ];
  char *filename_in, *filename_out;
  int errorcode;
  color TheColor;
  what_to_do directive;
  int r, g, b, x, y;
  int controlflag;

  /* In practise these will be set by the command-line arguments to the
     program. Haven't coded the command-line parsing stuff yet. */
  controlflag = 1;
  r = 192;
  g = 192;
  b = 192;
  x = 10;
  y = 10;

  if (argc > 1) {
    filename_in = argv[1];
  } else {
    filename_in =  "/afs/sipb.mit.edu/user/nocturne/project/tweb/test.gif";
  }

  if (argc > 2) {
    sscanf(argv[2], "%i", &x);
    sscanf(argv[3], "%i", &y);
  }
  
  filename_out = "testout.gif";
  
  if ((fpin = fopen(filename_in, "rb")) == NULL) {
    strcpy(buf, "Unable to read ");
    strcat(buf, filename_in);
    perror(buf);
    exit(-1);
  }
  
  errorcode = setjmp(jmpbuffer);
     
  if (errorcode != 0) {
    switch (errorcode) {
    case G_ERR_NOMEM:
      fprintf(stderr, "Cannot allocate necessary memory. Aborting.\n");
      exit(-1);
    default:
      fprintf(stderr, "We got here somehow.\n");
      exit(-1);
    }
  }

  TheColor.red = TheColor.grn = TheColor.blu = 256;




  /* again, in practise, the flow of control here will be specified */
  /* based on the command-line arguments. */
     
  if (controlflag == 0) {
    if ((fpout = fopen(filename_out, "wb")) == NULL) {
      strcpy(buf, "Unable to write to ");
      strcat(buf, filename_out);
      perror(buf);
      exit(-1);
    }
    init_trans_directive(&directive, r, g, b, fpout);
  } else if (controlflag == 1) {
    init_pixel_directive(&directive, x, y, &TheColor);
  }
    
  read_gif(fpin, &directive);

  if (controlflag == 1) {
    printf("Pixel colortable index is %i.\n", directive.answer);
  }

}
