# include "Ximage.h"

int PNGit () {

  FILE *f;
  png_structp png_ptr;
  png_infop info_ptr;
  png_color *palette;
  int Npalette;
  char filename[1024];
  int Nbytes, status;

  bDrawBuffer *buffer;

  /* expect a line telling the number of bytes and a filename */
  status = read (sock, filename, 16);
  filename[16] = 0;
  sscanf (filename, "%*s %d", &Nbytes);
  status = read (sock, filename, Nbytes);
  filename[status] = 0; /* make the string easy to parse */

  f = fopen (filename, "w");
  if (f == (FILE *) NULL) {
    fprintf (stderr, "can't open output file %s\n", "Xgraph.png");
    return (TRUE);  /* true because otherwise it quits kapa! */
  }

  png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, (png_voidp) NULL, (png_voidp) NULL, (png_voidp) NULL);
  if (!png_ptr) {
    fprintf (stderr, "can't get png structure\n");
    fclose (f);
    return (TRUE);
  }

  info_ptr = png_create_info_struct (png_ptr);
  if (!info_ptr) {
    fprintf (stderr, "can't get png info structure\n");
    png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
    fclose (f);
    return (TRUE);
  }

  if (setjmp (png_ptr[0].jmpbuf)) {
    fprintf (stderr, "can't get png return\n");
    png_destroy_write_struct (&png_ptr, &info_ptr);
    fclose (f);
    return (TRUE);
  }

  png_init_io (png_ptr, f);

  /* see docs for write-row-callback to provide progress info */

  png_set_IHDR (png_ptr, info_ptr, graphic.dx, graphic.dy, 8, PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); 

  /* png_set_IHDR (png_ptr, info_ptr, graphic.dx, graphic.dy, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); */

  palette = KapaPNGPalette (&Npalette);
  png_set_PLTE (png_ptr, info_ptr, palette, Npalette); 
 
  png_write_info (png_ptr, info_ptr);

  buffer = bDrawIt ();

  png_write_image (png_ptr, buffer[0].pixels);
  png_write_end (png_ptr, info_ptr);
  png_destroy_write_struct (&png_ptr, &info_ptr);
  
  bDrawBufferFree (buffer);
  free (palette);
  fclose (f);
  return (TRUE);

}
