//<copyright>
//
// Copyright (c) 1995-96
// Institute for Information Processing and Computer Supported New Media (IICM),
// Graz University of Technology, Austria.
//
//</copyright>


//<file>
//
//
// Name :       gifimage.C
//
// Purpose :    Implementation of class GifImage
//
// Created :    04 Jan 95    Bernhard Marschall
// Modified :   03 Aug 95    Bernhard Marschall
//
// $Id: gifimage.C,v 1.11 1997/02/19 09:20:14 bmarsch Exp $
//
// Description:
//
//</file>
//
// $Log: gifimage.C,v $
// Revision 1.11  1997/02/19 09:20:14  bmarsch
// Changed return value of HgRasterCallback::getData()
//
// Revision 1.10  1996/10/02 13:28:18  bmarsch
// verbose.h was moved from hyperg to utils
//
// Revision 1.9  1996/09/02 12:57:35  bmarsch
// Initialize buffer
//
// Revision 1.8  1996/03/01 14:22:23  bmarsch
// Adjusted to new alpha channel handling of ivRaster
//
// Revision 1.7  1996/02/29 12:42:32  bmarsch
// Always call decodedInterlaced() callback after a pass (also
// in finishDecode())
//


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
#include <setjmp.h>

#include "hgrastercb.h"
#include "gifimage.h"

//#define VERBOSE
#include <hyperg/utils/verbose.h>


// ************************************************************************
// These static variables are needed for the C (GIF decoder) to C++
// (callback) interface

static HgRasterCallback* the_callback = nil;
static char gifError[256];



/*
 * rdgif.c
 *
 * Copyright (C) 1991-1994, Thomas G. Lane.
 * This file is part of the Independent JPEG Group's software.
 * For conditions of distribution and use, see the accompanying README file.
 *
 * This file contains routines to read input images in GIF format.
 *
 * These routines may need modification for non-Unix environments or
 * specialized applications.  As they stand, they assume input from
 * an ordinary stdio stream.  They further assume that reading begins
 * at the start of the file; input_init may need work if the
 * user interface has already read some data (e.g., to determine that
 * the file is indeed GIF format).
 */

/*
 * This code is loosely based on giftoppm from the PBMPLUS distribution
 * of Feb. 1991.  That file contains the following copyright notice:
 * +-------------------------------------------------------------------+
 * | Copyright 1990, David Koblas.                                     |
 * |   Permission to use, copy, modify, and distribute this software   |
 * |   and its documentation for any purpose and without fee is hereby |
 * |   granted, provided that the above copyright notice appear in all |
 * |   copies and that both that copyright notice and this permission  |
 * |   notice appear in supporting documentation.  This software is    |
 * |   provided "as is" without express or implied warranty.           |
 * +-------------------------------------------------------------------+
 *
 * We are also required to state that
 *    "The Graphics Interchange Format(c) is the Copyright property of
 *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
 *    CompuServe Incorporated."
 */


// ************************************************************************
// error codes, messages, and handler
// most of it copied from IJG stuff

// buffer for longjmp (needed for error recovery)
static jmp_buf jmpState;

// "symbolic" error codes
enum {
  ERR_INPUT_EOF = 0,
  ERR_GIF_CODESIZE,
  ERR_GIF_IMAGENOTFOUND,
  ERR_GIF_NOT,
  WRN_GIF_BADDATA,
  WRN_GIF_CHAR,
  WRN_GIF_ENDCODE,
  WRN_GIF_NOMOREDATA
};

// number of parameters for error messages
static const int error_parameters[] = {
  0,
  1,
  0,
  0,
  0,
  1,
  0,
  0
};

// error messages
static const char* const error_messages[] = {
  "Premature end of input file",
  "Bogus GIF codesize %d",
  "Too few images in GIF file",
  "Not a GIF file",
  "Corrupt data in GIF file",
  "Bogus char 0x%02x in GIF file, ignoring",
  "Premature end of GIF image",
  "Ran out of GIF bits",
};

// called on warning: prints some message
static void error_message(int code, long p)
{
  if (error_parameters[code])
    sprintf(gifError, error_messages[code], p);
  else
    sprintf(gifError, error_messages[code]);
  if (the_callback) the_callback->error(gifError);
}

// called on error: prints some messages and does a longjmp
static void error_exit(int code, long p)
{
  error_message(code, p);
  longjmp(jmpState, 1);
}

// ************************************************************************
// defines and data types from jpeglib.h

#if defined(IRIX) || defined(AIX)
#define CHAR_IS_UNSIGNED
#else
#undef CHAR_IS_UNSIGNED
#endif

typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef long INT32;

typedef unsigned char SAMPLE;
typedef SAMPLE *SAMPROW;	/* ptr to one image row of pixel samples. */
typedef SAMPROW *SAMPARRAY;	/* ptr to some rows (a 2-D sample array) */

#define GETSAMPLE(value)  ((int) (value))

#define ERREXIT1(code, par) \
  error_exit(code, par)
#define ERREXIT(code) \
  ERREXIT1(code, 0)
#define WARNMS1(code, par) \
  error_message(code, par)
#define WARNMS(code) \
  WARNMS1(code, 0)

#define FREAD(file,buf,sizeofbuf)  \
  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))

// ************************************************************************
// replaces libjpeg's memory manager

static SAMPROW alloc_row(int cols)
{
  return (SAMPROW) malloc(cols * sizeof(SAMPLE));
}

static SAMPARRAY alloc_array(int cols, int rows)
{
  SAMPARRAY array = (SAMPARRAY) malloc(rows * sizeof(SAMPROW));

  for (int i = 0; i < rows; i++)
    array[i] = alloc_row(cols);

  return array;
}

static void free_row(SAMPROW row)
{
  free(row);
}

static void free_array(SAMPARRAY array, int rows)
{
  for (int i = 0; i < rows; i++)
    free_row(array[i]);
  free(array);
}

// ************************************************************************
// change macro ReadOk to give viewer a chance to load new data on EOF
// during loading

static inline boolean ReadOK(FILE* file, char* buffer, int len)
{
  int r = 0;

tryagain:
  r = FREAD(file, buffer, len);
  if (r < len) {
    if (the_callback && the_callback->loading()) {
      // get new data
      buffer += r;
      len -= r;
      if (!the_callback->getData())
        return 0;
      goto tryagain;
    }
    else
      return 0;
  }
  return 1;
}


// ************************************************************************
// GIF constants and macros

#define	MAXCOLORMAPSIZE	256	/* max # of colors in a GIF colormap */
#define NUMCOLORS	3	/* # of colors */
#define CM_RED		0	/* color component numbers */
#define CM_GREEN	1
#define CM_BLUE		2

#define	MAX_LZW_BITS	12	/* maximum LZW code size */
#define LZW_TABLE_SIZE	(1<<MAX_LZW_BITS) /* # of possible LZW symbols */

/* Macros for extracting header data --- note we assume chars may be signed */

#define LM_to_uint(a,b)		((((b)&0xFF) << 8) | ((a)&0xFF))

#define BitSet(byte, bit)	((byte) & (bit))
#define INTERLACE	0x40	/* mask for bit signifying interlaced image */
#define COLORMAPFLAG	0x80	/* mask for bit signifying colormap presence */


/* LZW decompression tables look like this:
 *   symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
 *   symbol_tail[K] = suffix byte   of any LZW symbol K (0..LZW_TABLE_SIZE-1)
 * Note that entries 0..end_code of the above tables are not used,
 * since those symbols represent raw bytes or special codes.
 *
 * The stack represents the not-yet-used expansion of the last LZW symbol.
 * In the worst case, a symbol could expand to as many bytes as there are
 * LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
 * (This is conservative since that number includes the raw-byte symbols.)
 *
 * The tables are allocated from FAR heap space since they would use up
 * rather a lot of the near data space in a PC.
 */
/* Private version of data source object */
typedef struct {
  unsigned int image_width;	/* input image width */
  unsigned int image_height;	/* input image height */
  FILE* input_file;             
  SAMPARRAY buffer;

  SAMPARRAY colormap;		/* GIF colormap (converted to my format) */

  /* State for GetCode and LZWReadByte */
  char code_buf[256+4];		/* current input data block */
  int last_byte;		/* # of bytes in code_buf */
  int last_bit;			/* # of bits in code_buf */
  int cur_bit;			/* next bit index to read */
  boolean out_of_blocks;	/* true if hit terminator data block */

  int input_code_size;		/* codesize given in GIF file */
  int clear_code,end_code;	/* values for Clear and End codes */

  int code_size;		/* current actual code size */
  int limit_code;		/* 2^code_size */
  int max_code;			/* first unused code value */
  boolean first_time;		/* flags first call to LZWReadByte */

  /* Private state for LZWReadByte */
  int oldcode;			/* previous LZW symbol */
  int firstcode;		/* first byte of oldcode's expansion */

  /* LZW symbol table and expansion stack */
  UINT16 *symbol_head;	/* => table of prefix symbols */
  UINT8 *symbol_tail;	/* => table of suffix bytes */
  UINT8 *symbol_stack;	/* => stack for symbol expansions */
  UINT8 *sp;		/* stack pointer */

  unsigned int cur_row_number;	/* need to know actual row number */

  /* State for interlaced image processing */
  boolean is_interlaced;   /* true if have interlaced image */
  unsigned int max_1;      /* max. row number for first pass */
  unsigned int max_2;      /* max. row number for second pass */
  unsigned int max_3;      /* max. row number for third pass */
  int copies;              /* number of additional copies of decoded row in output image */ 

  /* bmarsch: 19941220: support for transparency */
  int transparent;             // index of transparent color
  SAMPROW alpha;               // array for alpha channel
} gif_source_struct;

typedef gif_source_struct * gif_source_ptr;


static int
ReadByte (gif_source_ptr sinfo)
/* Read next byte from GIF file */
{
  register FILE * infile = sinfo->input_file;
  int c;

  // bmarsch: give viewer a chance to load new data on EOF
  while ((c = getc(infile)) == EOF) {
    if (the_callback && the_callback->loading()) {
      if (!the_callback->getData())
        ERREXIT(ERR_INPUT_EOF);
    }
    else {
      ERREXIT(ERR_INPUT_EOF);
    }
  }
  return c;
}


static int
GetDataBlock (gif_source_ptr sinfo, char *buf)
/* Read a GIF data block, which has a leading count byte */
/* A zero-length block marks the end of a data block sequence */
{
  int count;

  count = ReadByte(sinfo);
  if (count > 0) {
    if (! ReadOK(sinfo->input_file, buf, count))
      ERREXIT(ERR_INPUT_EOF);
  }
  return count;
}


static void
SkipDataBlocks (gif_source_ptr sinfo)
/* Skip a series of data blocks, until a block terminator is found */
{
  char buf[256];

  while (GetDataBlock(sinfo, buf) > 0)
    /* skip */;
}


static void
ReInitLZW (gif_source_ptr sinfo)
/* (Re)initialize LZW state; shared code for startup and Clear processing */
{
  sinfo->code_size = sinfo->input_code_size + 1;
  sinfo->limit_code = sinfo->clear_code << 1;	/* 2^code_size */
  sinfo->max_code = sinfo->clear_code + 2;	/* first unused code value */
  sinfo->sp = sinfo->symbol_stack;		/* init stack to empty */
}


static void
InitLZWCode (gif_source_ptr sinfo)
/* Initialize for a series of LZWReadByte (and hence GetCode) calls */
{
  /* GetCode initialization */
  sinfo->last_byte = 2;		/* make safe to "recopy last two bytes" */
  sinfo->last_bit = 0;		/* nothing in the buffer */
  sinfo->cur_bit = 0;		/* force buffer load on first call */
  sinfo->out_of_blocks = false;

  /* LZWReadByte initialization: */
  /* compute special code values (note that these do not change later) */
  sinfo->clear_code = 1 << sinfo->input_code_size;
  sinfo->end_code = sinfo->clear_code + 1;
  sinfo->first_time = true;
  ReInitLZW(sinfo);
}


static int
GetCode (gif_source_ptr sinfo)
/* Fetch the next code_size bits from the GIF data */
/* We assume code_size is less than 16 */
{
  register INT32 accum;
  int offs, ret, count;

  while ( (sinfo->cur_bit + sinfo->code_size) > sinfo->last_bit) {
    /* Time to reload the buffer */
    if (sinfo->out_of_blocks) {
      WARNMS(WRN_GIF_NOMOREDATA);
      return sinfo->end_code;	/* fake something useful */
    }
    /* preserve last two bytes of what we have -- assume code_size <= 16 */
    sinfo->code_buf[0] = sinfo->code_buf[sinfo->last_byte-2];
    sinfo->code_buf[1] = sinfo->code_buf[sinfo->last_byte-1];
    /* Load more bytes; set flag if we reach the terminator block */
    if ((count = GetDataBlock(sinfo, &sinfo->code_buf[2])) == 0) {
      sinfo->out_of_blocks = true;
      WARNMS(WRN_GIF_NOMOREDATA);
      return sinfo->end_code;	/* fake something useful */
    }
    /* Reset counters */
    sinfo->cur_bit = (sinfo->cur_bit - sinfo->last_bit) + 16;
    sinfo->last_byte = 2 + count;
    sinfo->last_bit = sinfo->last_byte * 8;
  }

  /* Form up next 24 bits in accum */
  offs = sinfo->cur_bit >> 3;	/* byte containing cur_bit */
#ifdef CHAR_IS_UNSIGNED
  accum = sinfo->code_buf[offs+2];
  accum <<= 8;
  accum |= sinfo->code_buf[offs+1];
  accum <<= 8;
  accum |= sinfo->code_buf[offs];
#else
  accum = sinfo->code_buf[offs+2] & 0xFF;
  accum <<= 8;
  accum |= sinfo->code_buf[offs+1] & 0xFF;
  accum <<= 8;
  accum |= sinfo->code_buf[offs] & 0xFF;
#endif

  /* Right-align cur_bit in accum, then mask off desired number of bits */
  accum >>= (sinfo->cur_bit & 7);
  ret = ((int) accum) & ((1 << sinfo->code_size) - 1);
  
  sinfo->cur_bit += sinfo->code_size;
  return ret;
}


static int
LZWReadByte (gif_source_ptr sinfo)
/* Read an LZW-compressed byte */
{
  register int code;		/* current working code */
  int incode;			/* saves actual input code */

  /* First time, just eat the expected Clear code(s) and return next code, */
  /* which is expected to be a raw byte. */
  if (sinfo->first_time) {
    sinfo->first_time = false;
    code = sinfo->clear_code;	/* enables sharing code with Clear case */
  } else {

    /* If any codes are stacked from a previously read symbol, return them */
    if (sinfo->sp > sinfo->symbol_stack)
      return (int) *(-- sinfo->sp);

    /* Time to read a new symbol */
    code = GetCode(sinfo);

  }

  if (code == sinfo->clear_code) {
    /* Reinit state, swallow any extra Clear codes, and */
    /* return next code, which is expected to be a raw byte. */
    ReInitLZW(sinfo);
    do {
      code = GetCode(sinfo);
    } while (code == sinfo->clear_code);
    if (code > sinfo->clear_code) { /* make sure it is a raw byte */
      WARNMS(WRN_GIF_BADDATA);
      code = 0;			/* use something valid */
    }
    /* make firstcode, oldcode valid! */
    sinfo->firstcode = sinfo->oldcode = code;
    return code;
  }

  if (code == sinfo->end_code) {
    /* Skip the rest of the image, unless GetCode already read terminator */
    if (! sinfo->out_of_blocks) {
      SkipDataBlocks(sinfo);
      sinfo->out_of_blocks = true;
    }
    /* Complain that there's not enough data */
    WARNMS(WRN_GIF_ENDCODE);
    /* Pad data with 0's */
    return 0;			/* fake something usable */
  }

  /* Got normal raw byte or LZW symbol */
  incode = code;		/* save for a moment */
  
  if (code >= sinfo->max_code) { /* special case for not-yet-defined symbol */
    /* code == max_code is OK; anything bigger is bad data */
    if (code > sinfo->max_code) {
      WARNMS(WRN_GIF_BADDATA);
      incode = 0;		/* prevent creation of loops in symbol table */
    }
    /* this symbol will be defined as oldcode/firstcode */
    *(sinfo->sp++) = (UINT8) sinfo->firstcode;
    code = sinfo->oldcode;
  }

  /* If it's a symbol, expand it into the stack */
  while (code >= sinfo->clear_code) {
    *(sinfo->sp++) = sinfo->symbol_tail[code]; /* tail is a byte value */
    code = sinfo->symbol_head[code]; /* head is another LZW symbol */
  }
  /* At this point code just represents a raw byte */
  sinfo->firstcode = code;	/* save for possible future use */

  /* If there's room in table, */
  if ((code = sinfo->max_code) < LZW_TABLE_SIZE) {
    /* Define a new symbol = prev sym + head of this sym's expansion */
    sinfo->symbol_head[code] = sinfo->oldcode;
    sinfo->symbol_tail[code] = (UINT8) sinfo->firstcode;
    sinfo->max_code++;
    /* Is it time to increase code_size? */
    if ((sinfo->max_code >= sinfo->limit_code) &&
	(sinfo->code_size < MAX_LZW_BITS)) {
      sinfo->code_size++;
      sinfo->limit_code <<= 1;	/* keep equal to 2^code_size */
    }
  }
  
  sinfo->oldcode = incode;	/* save last input symbol for future use */
  return sinfo->firstcode;	/* return first byte of symbol's expansion */
}


static void
ReadColorMap (gif_source_ptr sinfo, int cmaplen, SAMPARRAY cmap)
/* Read a GIF colormap */
{
  int i;

  for (i = 0; i < cmaplen; i++) {
    cmap[CM_RED][i]   = (SAMPLE) ReadByte(sinfo);
    cmap[CM_GREEN][i] = (SAMPLE) ReadByte(sinfo);
    cmap[CM_BLUE][i]  = (SAMPLE) ReadByte(sinfo);
  }
}


// bmarsch: 19941220: read Graphic Control Extension (GCE) to get
// index of transparent colour
// format of GCE:  Extension Introducer (0x21)     parsed of already
//                 Graphic Control Label (0xF9)
//                 Block Size (1 byte)             not counting EI, GCL, BS & Terminator
//                 Fields (1 byte)                 LSB == transparent flag
//                 Delay Time (2 byte)
//                 Transparent Color Index (1 byte)
//                 Terminator (1 byte)

static void
DoExtension (gif_source_ptr sinfo)
/* Process an extension block */
{
  int extlabel;
  int flags;
  int dummy;

  /* Read extension label byte */
  extlabel = ReadByte(sinfo);

  /* Skip the data block(s) associated with the extension */
//  SkipDataBlocks(sinfo);

  if (extlabel != 0xF9) {   // Graphic Control Label
    // error
    SkipDataBlocks(sinfo);
    return;
  }

  dummy = ReadByte(sinfo);   // Block Size
  flags = ReadByte(sinfo);   // flags
  dummy = ReadByte(sinfo);   // Delay Time (2 bytes)
  dummy = ReadByte(sinfo);
  if (flags & 0x1) {   // transparency flag set
    // store transparent color index
    sinfo->transparent = ReadByte(sinfo);
  }
  dummy = ReadByte(sinfo);   // Block Terminator
}


/*
 * Read the file header; return image size and component count.
 */

static void
start_input_gif (gif_source_ptr source)
{
  char hdrbuf[10];		/* workspace for reading control blocks */
  unsigned int width, height;	/* image dimensions */
  int colormaplen, aspectRatio;
  int c;

  /* Allocate space to store the colormap */
  source->colormap = alloc_array(MAXCOLORMAPSIZE, NUMCOLORS);

  /* Read and verify GIF Header */
  if (! ReadOK(source->input_file, hdrbuf, 6))
    ERREXIT(ERR_GIF_NOT);
  if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')
    ERREXIT(ERR_GIF_NOT);
  /* If version number is unknown, try to process anyway;
   * this is per recommendation in GIF89a standard.
   */

  /* Read and decipher Logical Screen Descriptor */
  if (! ReadOK(source->input_file, hdrbuf, 7))
    ERREXIT(ERR_INPUT_EOF);
  width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
  height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
  colormaplen = 2 << (hdrbuf[4] & 0x07);
  /* we ignore the color resolution, sort flag, and background color index */
  aspectRatio = hdrbuf[6] & 0xFF;

  /* Read global colormap if header indicates it is present */
  if (BitSet(hdrbuf[4], COLORMAPFLAG))
    ReadColorMap(source, colormaplen, source->colormap);

  /* Scan until we reach start of desired image.
   * We don't currently support skipping images, but could add it easily.
   */
  for (;;) {
    c = ReadByte(source);

    if (c == ';')		/* GIF terminator?? */
      ERREXIT(ERR_GIF_IMAGENOTFOUND);

    if (c == '!') {		/* Extension */
      DoExtension(source);
      continue;
    }
    
    if (c != ',') {		/* Not an image separator? */
      WARNMS1(WRN_GIF_CHAR, c);
      continue;
    }

    /* Read and decipher Local Image Descriptor */
    if (! ReadOK(source->input_file, hdrbuf, 9))
      ERREXIT(ERR_INPUT_EOF);
    /* we ignore top/left position info, also sort flag */
    width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
    height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
    source->is_interlaced = BitSet(hdrbuf[8], INTERLACE);

    /* Read local colormap if header indicates it is present */
    /* Note: if we wanted to support skipping images, */
    /* we'd need to skip rather than read colormap for ignored images */
    if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
      colormaplen = 2 << (hdrbuf[8] & 0x07);
      ReadColorMap(source, colormaplen, source->colormap);
    }

    source->input_code_size = ReadByte(source); /* get min-code-size byte */
    if (source->input_code_size < 2 || source->input_code_size >= MAX_LZW_BITS)
      ERREXIT1(ERR_GIF_CODESIZE, source->input_code_size);

    /* Reached desired image, so break out of loop */
    /* If we wanted to skip this image, */
    /* we'd call SkipDataBlocks and then continue the loop */
    break;
  }

  /* Prepare to read selected image: first initialize LZW decompressor */
  source->symbol_head = (UINT16*) malloc((size_t) LZW_TABLE_SIZE * sizeof(UINT16));
  source->symbol_tail = (UINT8*) malloc((size_t) LZW_TABLE_SIZE * sizeof(UINT8));
  source->symbol_stack = (UINT8*) malloc((size_t) LZW_TABLE_SIZE * sizeof(UINT8));
  InitLZWCode(source);

  /*
   * If image is interlaced, we read it into a full-size sample array,
   * decompressing as we go; then get_interlaced_row selects rows from the
   * sample array in the proper order.
   */
  if (source->is_interlaced) {
    // calculate maximum row numbers for each pass
    int h1 = height - 1;
    source->max_1 = (h1 >> 3) + 1;
    source->max_2 = (h1 >> 2) + 1;
    source->max_3 = (h1 >> 1) + 1;
  }

  /* Create compressor input buffer. */
  source->buffer = alloc_array(width * NUMCOLORS, 1);

  /* bmarsch: 19941220: create input buffer for alpha channel */
  source->alpha = alloc_row(width);

  /* Return info about the image. */
  source->image_width = width;
  source->image_height = height;
}


/*
 * Read one row of pixels.
 * This version is used for noninterlaced GIF images:
 * we read directly from the GIF file.
 */

static unsigned int
get_pixel_rows (gif_source_ptr source)
{
  register int c;
  register SAMPROW ptr;
  register unsigned int col;
  register SAMPARRAY colormap = source->colormap;

  /* bmarsch 19941220: support for transparency */
  register SAMPROW alpha = source->alpha;
  register int trans = source->transparent;
  
  ptr = source->buffer[0];
  for (col = source->image_width; col > 0; col--) {
    c = LZWReadByte(source);
    *ptr++ = colormap[CM_RED][c];
    *ptr++ = colormap[CM_GREEN][c];
    *ptr++ = colormap[CM_BLUE][c];
    /* bmarsch 19941220 */
    *alpha++ = (c == trans) ? 0 : 255;
  }

  // map number of decoded row to display row
  unsigned int& row = source->cur_row_number;
  unsigned int irow;

  if (source->is_interlaced) {
    if (row < source->max_1) {       // 1st pass
      irow = row << 3;
      source->copies = 8;
    }
    else if (row < source->max_2) {   // 2nd pass
      irow = ((row - source->max_1) << 3) + 4;
      source->copies = 4;
    }
    else if (row < source->max_3) {   // 3rd pass
      irow = ((row - source->max_2) << 2) + 2;
      source->copies = 2;
    }
    else {                            // 4th pass
      irow = ((row - source->max_3) << 1) + 1;
      source->copies = 1;
    }
  }
  else
    irow = row;

  row++;
  return irow;
}


/*
 * The module selection routine for GIF format input.
 */

static gif_source_ptr
jinit_read_gif ()
{
  gif_source_ptr source;

  /* Create module interface object */
  source = (gif_source_ptr) malloc(sizeof(gif_source_struct));

  /* bmarsch: 2 Sep 96: init */
  memset(source->code_buf, 0, 256+4);

  /* bmarsch: 19941220: transparency */
  source->transparent = -1;
  source->alpha = nil;
  source->cur_row_number = 0;
  source->copies = 1;

  return source;
}


// ************************************************************************
// class GifImpl
// implementation details of the GIF decoder

class GifImpl {
public:
  gif_source_ptr src_mgr_;           // source manager for decoding GIF's
};

// free all storage allocated by src_mgr_
static void destroy_gif_decompress(GifImpl* impl)
{
  gif_source_ptr& src = impl->src_mgr_;
  free_array(src->colormap, NUMCOLORS);
  free_array(src->buffer, 1);
  free_row(src->alpha);
  free(src->symbol_head);
  free(src->symbol_tail);
  free(src->symbol_stack);
}

// ************************************************************************

GifImage::GifImage(FILE* fp, const char* fname, Raster*& raster,
                   HgRasterCallback* cb, boolean dither)
: RasterImage(fp, fname, raster, cb, dither)
{
  DEBUGNL("GI::GI");
  the_callback = cb;

  impl_ = new GifImpl();

  // set up gif decoder
  gif_source_ptr src_mgr = jinit_read_gif();
  impl_->src_mgr_ = src_mgr;
  src_mgr->input_file = fp;

  // read header & set image size
  start_input_gif(src_mgr);
  setSize(src_mgr->image_width, src_mgr->image_height);

  DEBUGNL("GI::GI ok");
}

// ************************************************************************

GifImage::~GifImage()
{
  free(impl_->src_mgr_);
  delete impl_;
}

// ************************************************************************

void GifImage::decode(int numrows)
{
  DEBUGNL("GI::decode(" << numrows << ")");

  // do nothing if an error has occured
  if (error_) return;

  gif_source_ptr src_mgr = impl_->src_mgr_;

  // set entry point for error recovery
  if (setjmp(jmpState)) {
    destroy_gif_decompress(impl_);
    error_ = 1;
    return;
  }

  if (src_mgr->transparent >= 0) {
    DEBUGNL("GIF: transparency used");
    raster_->useAlphaTransparency();
  }

  int w3 = width() * 3;
  int maxrow = decoded_ + numrows;
  if (maxrow > src_mgr->image_height) maxrow = src_mgr->image_height;

  float incp = 1.0 / src_mgr->image_height;

  while (decoded_ < maxrow) {
    int row = get_pixel_rows(src_mgr);
    register Byte* pixptr = (Byte*) data() + row * w3;
    register Byte* adptr = (Byte*) alpha() + row * width();

    if (callback_)
      callback_->increaseProgress(incp);

    // Copy decoded row to data array. For interlaced images rows not
    // yet decoded are copied
    int copies = (row + src_mgr->copies > src_mgr->image_height) ?
                  src_mgr->image_height - row :
                  src_mgr->copies;
    while (copies--) {
      SAMPROW ptr = src_mgr->buffer[0];
      register Byte* asptr = src_mgr->alpha;
      for (register int x = 0; x < src_mgr->image_width; x++) {
        *pixptr++ = GETSAMPLE(*ptr++);
        *pixptr++ = GETSAMPLE(*ptr++);
        *pixptr++ = GETSAMPLE(*ptr++);
        if (src_mgr->transparent >= 0)
          *adptr++ = (GETSAMPLE(*asptr++)) ? 255 : 0;
      }
    }

    decoded_++;

    // live display
    if (callback_) {
      if (src_mgr->is_interlaced) {
        if ((decoded_ == src_mgr->max_1) ||
            (decoded_ == src_mgr->max_2) ||
            (decoded_ == src_mgr->max_3) ||
            (decoded_ == src_mgr->image_height))
          callback_->decodedInterlaced();
      }
      else {
        if (decoded_ % 20 == 0)
          callback_->decodedSequential(20);
        else if (decoded_ == src_mgr->image_height)
          callback_->decodedSequential(src_mgr->image_height % 20);
      }
    }
  }
}

// ************************************************************************

void GifImage::finishDecode()
{
  DEBUGNL("GI::finishDecode()");

  int left = height() - decoded_;
  if (left > 0) decode(left);

  // do nothing if an error has occured
  if (error_) return;

  destroy_gif_decompress(impl_);
}

// ************************************************************************

void GifImage::abortDecode()
{
  destroy_gif_decompress(impl_);
}
