/*
 * gif2png.c
 * Copyright (C) 1995 Alexander Lehmann
 * For conditions of distribution and use, see copyright notice in gif2png.h
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define PNG_INTERNAL
#include "gif2png.h"

#ifdef AMIGA
/* declare isatty() */
#include <fcntl.h>
#endif

struct GIFelement first={NULL};
struct GIFelement *current;
int delete;
int histogram;
int interlaced;
int progress;
int recover;
int software_chunk;
int skip_pte;

/* return the actual line # used to store an interlaced line */

int interlace_line(int height, int line)
{
  int res;

  if((line&7)==0) {
    return line>>3;
  }
  res=(height+7)>>3;
  if((line&7)==4) {
    return res+((line-4)>>3);
  }
  res+=(height+3)>>3;
  if((line&3)==2) {
    return res+((line-2)>>2);
  }
  return res+((height+1)>>2)+((line-1)>>1);
}

/* inverse function of above, used for recovery of interlaced images */

int inv_interlace_line(int height, int line)
{
  if((line<<3)<height) {
    return line<<3;
  }
  line-=(height+7)>>3;
  if((line<<3)+4<height) {
    return (line<<3)+4;
  }
  line-=(height+3)>>3;
  if((line<<2)+2<height) {
    return (line<<2)+2;
  }
  line-=(height+1)>>2;
  return (line<<1)+1;
}

/* do some adjustments of the color palette. We won't check for duplicate
   colors, this is probably only a very rare case, but we check if all used
   colors are grays, some GIF writers (e.g. some versions to ppmtogif) leave
   the unused entries uninitialized, which breaks the detection of grayscale
   images (e.g. in QPV). If the image is grayscale we will use color type 0,
   except when the transparency color is also appearing as a visible color. In
   this case we write a paletted image, another solution would be gray+alpha,
   but that would probably increase the image size too much.
   If there are only few gray levels (<=16), we try to create a 4 or less bit
   grayscale file, but if the gray levels do not fit into the necessary grid,
   we write a paletted image, e.g. if the image contains black, white and 50%
   gray, the grayscale image would require 8 bit, but the paletted image only
   2 bit. Even with filtering, the 8 bit file will be larger.
*/

int graycheck(png_color c)
{
  /* check if r==g==b, moved to function to work around NeXTstep 3.3 cc bug.
   * life could be so easy if at least the basic tools worked as expected.
   */
  return c.red==c.green && c.green==c.blue;
}

int writefile(struct GIFelement *s, struct GIFelement *e, FILE *fp, int lastimg)
{
  int i;
  struct GIFimagestruct *img=e->imagestruct;
  unsigned long *count=img->color_count;
  GifColor *colors=img->colors;
  int gray;
  int last_color=0, colors_used=0;
  byte remap[MAXCMSIZE];
  int low_presc;
  png_struct *png_ptr = xalloc(sizeof (png_struct));
  png_info *info_ptr = xalloc(sizeof (png_info));
  int p;
  int bitdepth, gray_bitdepth;
  png_byte pal_trans[MAXCMSIZE];
  png_color_16 color16trans, color16back;
  byte buffer[24]; /* used for gIFt and gIFg */
  byte *data;
  int j;
  png_uint_16 histogr[MAXCMSIZE];
  unsigned long hist_maxvalue;
  int passcount;
  png_text software;

  if(img->trans!=-1 && !count[img->trans])
    img->trans=-1;

  gray=1;

  for(i=0;i<MAXCMSIZE;i++)
    if(count[i]) {
      gray &= graycheck(colors[i]);
      colors_used++;
      if(last_color<i) last_color=i;
    }

  if(gray) {
    fprintf(stderr, "image is grayscale\n");

    /* zero out unused colors */

    for(i=0;i<MAXCMSIZE;i++)
      if(!count[i]) {
        colors[i].red=colors[i].green=colors[i].blue=0;
      }

    if(img->trans!=-1) {
      for(i=0;i<MAXCMSIZE;i++) {
        if(i!=img->trans && colors[i].red==colors[img->trans].red) {
          gray=0;
          fprintf(stderr, "trans color is repeated in visible colors, using palette\n");
          break;
        }
      }
    }
  }

  bitdepth=8;
  if(last_color<16) bitdepth=4;
  if(last_color<4) bitdepth=2;
  if(last_color<2) bitdepth=1;

  if(gray) {
    for(i=0;i<MAXCMSIZE;i++)
      remap[i]=colors[i].red;
  }

  if(gray) {
    gray_bitdepth=8;

    /* try to adjust to 4 bit prescision grayscale */

    low_presc=1;
    for(i=0;i<MAXCMSIZE;i++) {
      if((remap[i]&0xf)*0x11!=remap[i]) {
        low_presc=0;
        break;
      }
    }
    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 0xf;
      }
      gray_bitdepth=4;
    }

    /* try to adjust to 2 bit prescision grayscale */

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        if((remap[i]&3)*5!=remap[i]) {
          low_presc=0;
          break;
        }
      }
    }

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 3;
      }
      gray_bitdepth=2;
    }

    /* try to adjust to 1 bit prescision grayscale */

    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        if((remap[i]&1)*3!=remap[i]) {
          low_presc=0;
          break;
        }
      }
    }
    if(low_presc) {
      for(i=0;i<MAXCMSIZE;i++) {
        remap[i] &= 1;
      }
      gray_bitdepth=1;
    }

    if(bitdepth<gray_bitdepth) {
      gray=0; /* write palette file */
    } else {
      bitdepth=gray_bitdepth;
    }
  }

  fprintf(stderr, "%d colors used, highest color %d, %s, bitdepth %d\n", colors_used, last_color, gray ? "gray":"palette", bitdepth);

  if(setjmp(png_ptr->jmpbuf)) {
    fprintf(stderr, "setjmp returns error condition\n");

    free(png_ptr);
    free(info_ptr);

    return 1;
  }

  png_write_init(png_ptr);
  png_info_init(info_ptr);
  png_init_io(png_ptr, fp);
  info_ptr->width=current->imagestruct->width;
  info_ptr->height=current->imagestruct->height;
  info_ptr->bit_depth=bitdepth;
  info_ptr->color_type=gray ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_PALETTE;
  info_ptr->interlace_type=interlaced;

  if(GifScreen.AspectRatio!=0 && GifScreen.AspectRatio!=49) {
    info_ptr->x_pixels_per_unit=GifScreen.AspectRatio+15;
    info_ptr->y_pixels_per_unit=64;
    info_ptr->phys_unit_type=PNG_RESOLUTION_UNKNOWN;
    info_ptr->valid |= PNG_INFO_pHYs;
  }

  if(img->offset_x>0 && img->offset_y>0) {
    info_ptr->x_offset=img->offset_x;
    info_ptr->y_offset=img->offset_y;
    info_ptr->offset_unit_type=PNG_OFFSET_PIXEL;
    info_ptr->valid |= PNG_INFO_oFFs;
  }

  if(GifScreen.Background>0) { /* no background for palette entry 0 */
    /* if the backgroup color doesn't appear in local palette, we just
       leave it out, if the pic is part of an animation, at least some will
       use the global palette */

    if(gray) {
      if(graycheck(GifScreen.ColorMap[GifScreen.Background])) {
        color16back.gray=remap[GifScreen.Background];
        info_ptr->background=color16back;
        info_ptr->valid |= PNG_INFO_bKGD;
      }
    } else {
      for(i=0;i<MAXCMSIZE;i++) {
        if(GifScreen.ColorMap[GifScreen.Background].red==colors[i].red &&
           GifScreen.ColorMap[GifScreen.Background].green==colors[i].green &&
           GifScreen.ColorMap[GifScreen.Background].blue==colors[i].blue) {
          if(last_color<i) last_color=i;
          color16back.index=i;
          info_ptr->background=color16back;
          info_ptr->valid |= PNG_INFO_bKGD;
          break;
        }
      }
    }
  }

  if(img->trans != -1) {
    if(gray) {
      color16trans.gray=remap[img->trans];
      info_ptr->trans_values=color16trans;
    } else {
      for(i=0;i<MAXCMSIZE;i++) pal_trans[i]=255;
      pal_trans[img->trans]=0;
      info_ptr->trans=pal_trans;
      info_ptr->num_trans=img->trans+1;
    }
    info_ptr->valid |= PNG_INFO_tRNS;
  }

  if(!gray) {
    info_ptr->palette=current->imagestruct->colors;
    info_ptr->num_palette=last_color+1;
    info_ptr->valid |= PNG_INFO_PLTE;
  }

  if(histogram && !gray) {
    /* histogram are not supported for grayscale images */
    hist_maxvalue=0;
    for(i=0;i<MAXCMSIZE;i++)
      if(count[i]>hist_maxvalue)
        hist_maxvalue=count[i];
    if(hist_maxvalue<=65535) {
      /* no scaling necessary */
      for(i=0;i<MAXCMSIZE;i++)
        histogr[i]=(png_uint_16)count[i];
    } else {
      for(i=0;i<MAXCMSIZE;i++)
        if(count[i]) {
          histogr[i]=(png_uint_16)
#ifdef __GO32__
          /* avoid using fpu instructions on djgpp, so we don't need emu387 */
                                   (((long long)count[i]*65535)/hist_maxvalue);
#else
                                   ((double)count[i]*65535.0/hist_maxvalue);
#endif
          if(histogr[i]==0)
            histogr[i]=1;
        } else {
          histogr[i]=0;
        }
    }
    info_ptr->hist=histogr;
    info_ptr->valid |= PNG_INFO_hIST;
  }

  if(software_chunk) {
    software.compression=-1;
    software.key="Software";
    software.text=(char*)version;
    software.text_length=strlen(software.text);

    info_ptr->num_text=1;
    info_ptr->max_text=1;
    info_ptr->text=&software;
  }

  png_write_info(png_ptr, info_ptr);

  info_ptr->num_text=0;
  info_ptr->max_text=0;
  info_ptr->text=NULL;

  if(info_ptr->bit_depth<8)
    png_set_packing(png_ptr);

  /* loop over elements until we reach the image or the last element if
     this is the last image in a GIF */

  while(lastimg ? s!=NULL : s != e->next) {
    switch((byte)s->GIFtype) {
      case GIFimage:
        passcount=png_set_interlace_handling(png_ptr);
        for(p=0;p<passcount;p++)
          for(i=0;i<current->imagestruct->height;i++) {
            if(progress) {
              if(passcount>1)
                printf("%d/%d ", p+1, passcount);
              printf("%2d%%\r", (int)(((long)i*100)/current->imagestruct->height));
              fflush(stdout);
            }
            data=access_data(current, (long) (img->interlace ?
                             interlace_line(current->imagestruct->height,i) : i) *
                             current->imagestruct->width,
                             current->imagestruct->width);
#ifndef TMPFILE
            /* if we store the image in memory, we have to remap once */
            if(gray && p==0) {
#else
            /* if we store the image in a file, we have to remap each time */
            if(gray) {
#endif
              for(j=0;j<img->width;j++) {
                data[j]=remap[data[j]];
              }
            }
            png_write_row(png_ptr, data);
          }
        break;

      case GIFcomment:
        data=access_data(s, 0, s->size);
        if(s->size<500) {
          png_write_tEXt(png_ptr, "Comment", data, s->size);
        } else {
          png_write_zTXt(png_ptr, "Comment", data, s->size, 0);
        }
        break;

      case GIFapplication:
        data=access_data(s, 0, s->size);
        png_write_chunk_start(png_ptr, "gIFx", s->size);
        png_write_chunk_data(png_ptr, data, s->size);
        png_write_chunk_end(png_ptr);
        break;

/* Plain Text Extensions are currently not support due to an unresolved issue
   about transparency. Since there are practically no GIFs around that use
   this, this will not be a problem, but a future version of this program
   will probably support PTEs in full.
*/
#if 0
      case GIFplaintext:
        data=access_data(s, 0, s->size);
        /* gIFt is 12 bytes longer than GCE, due to 32 bit ints and
           rgb colors */
        png_write_chunk_start(png_ptr, "gIFt", s->size+12);
        memset(buffer, 0, 24);
        buffer[2]=data[1];
        buffer[3]=data[0];
        buffer[6]=data[3];
        buffer[7]=data[2];
        buffer[10]=data[5];
        buffer[11]=data[4];
        buffer[14]=data[7];
        buffer[15]=data[6];
        buffer[16]=data[8];
        buffer[17]=data[9];
        buffer[18]=GifScreen.ColorMap[data[10]].red;
        buffer[19]=GifScreen.ColorMap[data[10]].green;
        buffer[20]=GifScreen.ColorMap[data[10]].blue;
        buffer[21]=GifScreen.ColorMap[data[11]].red;
        buffer[22]=GifScreen.ColorMap[data[11]].green;
        buffer[23]=GifScreen.ColorMap[data[11]].blue;
        png_write_chunk_data(png_ptr, buffer, 24);
        png_write_chunk_data(png_ptr, data+12, s->size-12);
        png_write_chunk_end(png_ptr);
        break;
#endif

      case GIFgraphicctl:
        data=access_data(s, 0, s->size);
        buffer[0]=(data[0]>>2)&7;
        buffer[1]=(data[0]>>1)&1;
        buffer[2]=data[2];
        buffer[3]=data[1];

        png_write_chunk(png_ptr, "gIFg", buffer, 4);
        break;

      default:
        fprintf(stderr, "gif2png internal error: encountered unused element type %c\n", s->GIFtype);
        break;
      }
    s=s->next;
  }
  png_write_end(png_ptr, info_ptr);
  png_write_destroy(png_ptr);

  free(png_ptr);
  free(info_ptr);

  return 0;
}

int processfile(char *fname, FILE *fp)
{
  char outname[1025]; /* MAXPATHLEN comes under too many names */
  int num_pics;
  struct GIFelement *start;
  int i;
  char *file_ext;

  if(fp==NULL) return 1;

#ifdef TMPFILE
  fseek(tempfile, 0, SEEK_SET);
#endif

  current=&first;

  num_pics=ReadGIF(fp);

  fclose(fp);

  if(num_pics>=0)
    printf("number of images %d\n", num_pics);

  if(num_pics<=0) return 1;

  /* create output filename */

  strcpy(outname, fname);

  file_ext=outname+strlen(outname)-4;
  if(strcmp(file_ext, ".gif")!=0 && strcmp(file_ext, ".GIF")!=0 &&
     strcmp(file_ext, "_gif")!=0 && strcmp(file_ext, "_GIF")!=0) {
    /* try to derive basename */
    file_ext=outname+strlen(outname);
    while(file_ext>=outname) {
      if(*file_ext=='.' || *file_ext=='/' || *file_ext=='\\') break;
      file_ext--;
    }
    if(file_ext<outname || *file_ext!='.') {
      /* as a last resort, just add .png to the filename */
      file_ext=outname+strlen(outname);
    }
  }

  strcpy(file_ext, ".png"); /* images are named .png, .p01, .p02, ... */

  start=NULL;

  i=0;

  for(current=first.next; current ; current=current->next) {
    if(start==NULL) start=current;
    if(current->GIFtype==GIFimage) {
      i++;
      if((fp=fopen(outname, "wb"))==NULL) {
        perror(outname);
        return 1;
      } else {
        writefile(start, current, fp, i==num_pics);
        fclose(fp);
        start=NULL;
        sprintf(file_ext, ".p%02d", i);
      }
    }
  }

  free_mem();

  if(delete) {
    /* we'll rename the GIF file, maybe a release version of this program will
       actually delete the file */
    strcpy(outname, fname);
    outname[strlen(outname)-1]='_';
    rename(fname, outname);
  }

  return 0;
}

/* check if stdin is a terminal, if your compiler is lacking isatty or fileno
   (non-ANSI functions), just return 0
*/

int input_is_terminal(void)
{
  return isatty(fileno(stdin));
}

int main(int argc, char *argv[])
{
  FILE *fp;
  int i;
  int errors=0;
  char name[1025];
  int ac;

  fprintf(stderr, "%s %s\n", version, compile_info);

#ifdef TMPFILE
  if((tempfile=tmpfile())==NULL) {
    perror("tempfile");
    exit(1);
  }
#endif

  software_chunk=1;
  progress=1;

  ac=1;

  for(ac=1; ac<argc && argv[ac][0]=='-'; ac++)
    for(i=1;i<strlen(argv[ac]);i++)
      switch(argv[ac][i]) {
        case 'd':
          delete=1;
          break;

        case 'h':
          histogram=1;
          break;

        case 'i':
          interlaced=1;
          break;

        case 'p':
          progress=0;
          break;

        case 'r':
          recover=1;
          break;

        case 's':
          software_chunk=0;
          break;

        case 't':
          skip_pte=1;
          break;

        default:
          fprintf(stderr, "unknown option char `%c'\n", argv[ac][i]);
usage:
          fprintf(stderr,
"usage: gif2png [ -dhi ] [file[.gif]] ...\n"
"\n"
"       -d delete source GIF files after successful conversion\n"
"       -i create interlaced PNG files\n"
"       -h create histogram chunks for color files\n"
"       -p do not display progress of PNG writing in %%\n"
"       -r try to recover corrupt GIF files\n"
"       -s do not write Software chunk\n"
"       -t ignore Plain Text Extensions\n"
"\n"
"       if no source files are listed, stdin is converted to noname.png\n"
"       (may not work on systems that distinguish between text and binary mode)\n"
"\n"
"       gif2png is Copyright 1995 by Alexander Lehmann <alex@hal.rhein-main.de>\n"
"       For copyright, license, credits, etc. see the file README, which you\n"
"       should have received along with this program. If you didn't, you may be\n"
"       able to find gif2png on ftp://ftp.uu.net/graphics/png or on my\n"
"       WWW-page http://www.student.informatik.th-darmstadt.de/~alexlehm/\n"
          );
          return 1;
      }

  /* loop over arguments or use stdin */
  if(argc==ac) {
    if(input_is_terminal()) {
      goto usage;
    }
    printf("stdin:\n");
    processfile("noname.gif", stdin);
  } else {
    for(i=ac;i<argc;i++) {
      strcpy(name, argv[i]);
      if((fp=fopen(name, "rb"))==NULL) {
        /* retry with .gif appended */
        strcat(name, ".gif");
        fp=fopen(name,"rb");
      }
      if(fp==NULL) {
        perror(argv[i]);
        errors=1;
      } else {
        printf("%s:\n", name);
        errors |= processfile(name, fp);
        /* fp is closed in processfile */
      }
    }
  }

  return errors;
}
