#include <stdio.h>
#include <malloc.h>
#include <vga.h>
#include "vgaui.h"
#include "xvgif.h"

#define min(x,y) (x<y?x:y)

int DEBUG = 0;

extern char *version;
extern char *progname;
extern vga_image image;

extern char (*vga_key_callback) (char);

char
mykeycallback (char c)
{

  switch (c) {
  case '+':
    /* Nothing bound yet - maybe use for contrast adjusting ? */
    return 0;
  case '-':
    /* Nothing bound yet - maybe use for contrast adjusting ? */
    return 0;
  }
  return 1;
}

void
main (int argc, char **argv)
{
  progname = argv[0];
  vga_key_callback = mykeycallback;
  if (argc > 1 && argv[1]) {
    vga_init ();
    decode (argv[1]);
    display (argv, 1);
  }
}

void
decode (char *fname)
{
  int i,
    j,
    len;
  PICINFO pinfo;

  if (fname && (i = LoadGIF (fname, &pinfo))) {
    image.filename = fname;
    image.wid = pinfo.w;
    image.ht = pinfo.h;

    if (!image.rgb)
      image.rgb = malloc (256 * 3 * sizeof (int));
    for (i = 0; i < 256 * 3; i += 3) {
      image.rgb[i] = pinfo.r[i / 3] >> 2;
      image.rgb[i + 1] = pinfo.g[i / 3] >> 2;
      image.rgb[i + 2] = pinfo.b[i / 3] >> 2;
    }
    if (image.data)
      free (image.data);
    image.data = malloc (pinfo.h * sizeof (char *));
    for (i = 0; i < image.ht; i++) {
      image.data[i] = malloc (image.wid);
      bcopy (pinfo.pic + i * image.wid, image.data[i], image.wid);
    }
    /* Free up the image */
    if (pinfo.pic)
      free (pinfo.pic);
    if (pinfo.comment)
      free (pinfo.comment);
  } else {
    fprintf (stderr, "%s: can't load %s as a gif file.\n\treader returned %d\n", progname, fname, i);
    exit (1);
  }
}
