/////////////////////////////////////////////////////////////////////////
//
// ISABEL: A group collaboration tool for the Internet
// Copyright (C) 2009 Agora System S.A.
// 
// This file is part of Isabel.
// 
// Isabel is free software: you can redistribute it and/or modify
// it under the terms of the Affero GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Isabel is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// Affero GNU General Public License for more details.
// 
// You should have received a copy of the Affero GNU General Public License
// along with Isabel.  If not, see <http://www.gnu.org/licenses/>.
//
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//
// $Id: gifEnc.cc 10798 2007-09-12 16:38:33Z gabriel $
//
/////////////////////////////////////////////////////////////////////////

#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#include <icf2/notify.hh>

#include "gifImpl.hh"

void
putByte (u8 *&dst, u8 src)
{
  *dst= src;
  dst++;
}

// put a u16 in GIF order (LSB first)
void
putLSBWord (u8 *&dst, u16 src)
{
  putByte(dst, src & 0xff);
  putByte(dst, (src>>8)&0xff);
}

void
putNBytes (u8 *&dst, u8 *src, int size)
{
  memcpy (dst, src, size);
  dst+= size;
}


typedef long int        count_int;

static char *comment=NULL; //"ISABEL GIF compressed";

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



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


static unsigned long cur_accum;
static int           cur_bits;




#define min(a,b)        ((a>b) ? b : a)

#define XV_BITS 12    /* BITS was already defined on some systems */

#define HSIZE  5003            /* 80% occupancy */

typedef unsigned char   char_type;


static int n_bits;                    /* number of bits/code */
static int maxbits = XV_BITS;         /* user settable max # bits/code */
static int maxcode;                   /* maximum code, given n_bits */
static int maxmaxcode = 1 << XV_BITS; /* NEVER generate this */

#define MAXCODE(n_bits)     ( (1 << (n_bits)) - 1)

static  count_int      htab [HSIZE];
static  unsigned short codetab [HSIZE];
#define HashTabOf(i)   htab[i]
#define CodeTabOf(i)   codetab[i]

static int hsize;            /* for dynamic table sizing */

/*
 * To save much memory, we overlay the table used by compress() with those
 * used by decompress().  The tab_prefix table is the same size and type
 * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
 * get this from the beginning of htab.  The output stack uses the rest
 * of htab, and contains characters.  There is plenty of room for any
 * possible stack (stack used to be 8000 characters).
 */

#define tab_prefixof(i)        CodeTabOf(i)
#define tab_suffixof(i)        ((u8 *)(htab))[i]
#define de_stack               ((u8 *)&tab_suffixof(1<<XV_BITS))

static int free_ent = 0;                  /* first unused entry */

/*
 * block compression parameters -- after all codes are used up,
 * and compression rate changes, start over.
 */
static int clear_flg = 0;

static long int in_count = 1;            /* length of input */
static long int out_count = 0;           /* # of codes output (for debugging) */

/*
 * compress stdin to stdout
 *
 * Algorithm:  use open addressing double hashing (no chaining) on the
 * prefix code / next character combination.  We do a variant of Knuth's
 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
 * secondary probe.  Here, the modular division first probe is gives way
 * to a faster exclusive-or manipulation.  Also do block compression with
 * an adaptive reset, whereby the code table is cleared when the compression
 * ratio decreases, but after the table fills.  The variable-length output
 * codes are re-sized at this point, and a special CLEAR code is generated
 * for the decompressor.  Late addition:  construct the table according to
 * file size for noticeable speed improvement on small files.  Please direct
 * questions about this implementation to ames!jaw.
 */

static int g_init_bits;

static int ClearCode;
static int EOFCode;

/******************************************************************************
 *
 * GIF Specific routines
 *
 ******************************************************************************/

/*
 * Number of characters so far in this 'packet'
 */
static int a_count;

/*
 * Set up the 'byte output' routine
 */
static void char_init()
{
    a_count = 0;
}

/*
 * Define the storage for the packet accumulator
 */
static u8 accum[ 256 ];

/*
 * Flush the packet to disk, and reset the accumulator
 */
static void flush_char(u8 *&p)
{
    if ( a_count > 0 )
    {
        putByte(p, a_count);
        putNBytes(p, accum, a_count);
        a_count = 0;
    }
}


/*
 * Add a character to the end of the current packet, and if it is 254
 * characters, flush the packet to disk.
 */
static void char_out(u8 *&p, int c)
{
    accum[ a_count++ ] = c;
    if ( a_count >= 254 )
    {
        flush_char(p);
    }
}


/*****************************************************************
 * TAG( output )
 *
 * Output the given code.
 * Inputs:
 *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
 *              that n_bits =< (long)wordsize - 1.
 * Outputs:
 *      Outputs code to the file.
 * Assumptions:
 *      Chars are 8 bits long.
 * Algorithm:
 *      Maintain a BITS character long buffer (so that 8 codes will
 * fit in it exactly).  Use the VAX insv instruction to insert each
 * code in turn.  When the buffer fills up empty it and start over.
 */

static unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
                                 0x001F, 0x003F, 0x007F, 0x00FF,
                                 0x01FF, 0x03FF, 0x07FF, 0x0FFF,
                                 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF
                               };

static void output(u8 *&p, int code)
{
  cur_accum &= masks[cur_bits];

  if (cur_bits > 0)
    cur_accum |= ((long)code << cur_bits);
  else
    cur_accum = code;

  cur_bits += n_bits;

  while ( cur_bits >= 8 )
  {
    char_out(p, (int) (cur_accum & 0xff) );
    cur_accum >>= 8;
    cur_bits -= 8;
  }

  /*
   * If the next entry is going to be too big for the code size,
   * then increase it, if possible.
   */

  if (free_ent > maxcode || clear_flg)
  {
    if ( clear_flg )
    {
      maxcode = MAXCODE (n_bits = g_init_bits);
      clear_flg = 0;
    }
    else
    {
      n_bits++;
      if ( n_bits == maxbits )
        maxcode = maxmaxcode;
      else
        maxcode = MAXCODE(n_bits);
    }
  }

  if ( code == EOFCode )
  {
    /* At EOF, write the rest of the buffer */
    while ( cur_bits > 0 )
    {
      char_out(p, (int)(cur_accum & 0xff) );
      cur_accum >>= 8;
      cur_bits -= 8;
    }

    flush_char(p);
  }
}

/********************************/
static void cl_hash(count_int hsize)          /* reset code table */
{
  count_int *htab_p = htab+hsize;
  long i;
  long m1 = -1;

  i = hsize - 16;
  do                              /* might use Sys V memset(3) here */
  {
    *(htab_p-16) = m1;
    *(htab_p-15) = m1;
    *(htab_p-14) = m1;
    *(htab_p-13) = m1;
    *(htab_p-12) = m1;
    *(htab_p-11) = m1;
    *(htab_p-10) = m1;
    *(htab_p-9) = m1;
    *(htab_p-8) = m1;
    *(htab_p-7) = m1;
    *(htab_p-6) = m1;
    *(htab_p-5) = m1;
    *(htab_p-4) = m1;
    *(htab_p-3) = m1;
    *(htab_p-2) = m1;
    *(htab_p-1) = m1;
    htab_p -= 16;
  } while ((i -= 16) >= 0);

  for ( i += 16; i > 0; i-- )
    *--htab_p = m1;
}



/********************************/
static void cl_block (u8 *&p)             /* table clear for block compress */
{
  /* Clear out the hash table */

  cl_hash ( (count_int) hsize );
  free_ent = ClearCode + 2;
  clear_flg = 1;

  output(p, ClearCode);
}


/********************************************************/
static void
compress(u8 *&p, int init_bits, const u8 *data, int len, u8 *pc2nc)
{
  long fcode;
  int i = 0;
  int c;
  int ent;
  int disp;
  int hsize_reg;
  int hshift;

  /*
   * Set up the globals:  g_init_bits - initial number of bits
   */
  g_init_bits = init_bits;

  /* initialize 'compress' globals */
  maxbits = XV_BITS;
  maxmaxcode = 1<<XV_BITS;
  memset((void *)htab,    0, (size_t)sizeof(htab));
  memset((void *)codetab, 0, (size_t)sizeof(codetab));
  hsize = HSIZE;
  free_ent = 0;
  clear_flg = 0;
  in_count = 1;
  out_count = 0;
  cur_accum = 0;
  cur_bits = 0;


  /*
   * Set up the necessary values
   */
  out_count = 0;
  clear_flg = 0;
  in_count = 1;
  maxcode = MAXCODE(n_bits = g_init_bits);

  ClearCode = (1 << (init_bits - 1));
  EOFCode = ClearCode + 1;
  free_ent = ClearCode + 2;

  char_init();
  ent = pc2nc[*data++];  len--;

  hshift = 0;
  for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
    hshift++;
  hshift = 8 - hshift;                /* set hash code range bound */

  hsize_reg = hsize;
  cl_hash( (count_int) hsize_reg);            /* clear hash table */

  output(p, ClearCode);

  while (len)
  {
    c = pc2nc[*data++];  len--;
    in_count++;

    fcode = (long) ( ( (long) c << maxbits) + ent);
    i = (((int) c << hshift) ^ ent);    /* xor hashing */

    if ( HashTabOf (i) == fcode )
    {
      ent = CodeTabOf (i);
      continue;
    }

    else if ( (long)HashTabOf (i) < 0 )      /* empty slot */
      goto nomatch;

    disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
    if ( i == 0 )
      disp = 1;

probe:
    if ( (i -= disp) < 0 )
      i += hsize_reg;

    if ( HashTabOf (i) == fcode )
    {
      ent = CodeTabOf (i);
      continue;
    }

    if ( (long)HashTabOf (i) >= 0 )
      goto probe;

nomatch:
    output(p, ent);
    out_count++;
    ent = c;

    if ( free_ent < maxmaxcode )
    {
      CodeTabOf (i) = free_ent++; /* code -> hashtable */
      HashTabOf (i) = fcode;
    }
    else
      cl_block(p);
  }

  /* Put out the final code */
  output(p, ent);
  out_count++;
  output(p, EOFCode);
}


int
gifEncodeFromRGB24(u8 *dst, int dstLen, const u8 *src, unsigned w, unsigned h)
{
    assert("gifEncodeFromRGB24 not yet implemented!!");
    // to be done

    return -1;
}

u8*
gifEncodeFromClut8(const u8 *b,
                   const u8 *colmap,
                   unsigned numColors,
                   unsigned w,
                   unsigned h
                  )
{
    // no patologycal cases, please
    u8 *buffer=(u8*)malloc (w*h+(w*h>>8)+16*1024), *p=buffer;
    u8  Interlace;
    u8  Background;
    u8  BitsPerPixel;
    u16  ColorMapSize;
    u8  InitCodeSize;
    u16 RWidth, Width, RHeight, Height, LeftOfs, TopOfs;

    u8  ch, pc2nc[256], packedColorMap[256][3];
    unsigned i, j, nc;

    Interlace = 0;
    Background = 0;

    // compact the pallete, removing duplicated colors
    nc = 0;

    for (i=0; i<numColors; i++)
    {
        // see if color #i is already used
        for (j=0; j<i; j++)
        {
          if (colmap[3*i] == colmap[3*j] && colmap[3*i+1] == colmap[3*j+1] &&
              colmap[3*i+2] == colmap[3*j+2]) break;
        }

        if (j == i)    /* wasn't found */
        {
          pc2nc[i] = nc;
          packedColorMap[nc][0] = colmap[3*i];
          packedColorMap[nc][1] = colmap[3*i+1];
          packedColorMap[nc][2] = colmap[3*i+2];
          nc++;
        }
        else pc2nc[i] = pc2nc[j];
    }

    // figure out 'BitsPerPixel'
    for (i= 1; i < 8; i++)
        if ( (unsigned)(1<<i) >= nc) break;

    BitsPerPixel = i;

    ColorMapSize = 1 << BitsPerPixel;

    RWidth  = Width  = w;
    RHeight = Height = h;
    LeftOfs = TopOfs = 0;

    if (BitsPerPixel <= 1) InitCodeSize = 2;
                      else InitCodeSize = BitsPerPixel;

#if 0
    NOTIFY("GIF decoder: "
           "pic=0x%p, w,h=%dx%d, numcols=%d, Bits=%d,Cmapsize=%d\n",
           b, w,h,nc,BitsPerPixel,ColorMapSize
          );
#endif

    if (comment && strlen(comment) > (size_t) 0)
    {
        putNBytes(p, (u8*)"GIF89a", 6);   // the GIF magic number
    }
    else
    {
        putNBytes(p, (u8*)"GIF87a", 6);   // the GIF magic number
    }

    putLSBWord(p, RWidth);                // screen descriptor
    putLSBWord(p, RHeight);

    ch = 0x80;                   // Yes, there is a color map
    ch |= (8-1)<<4;              // OR in the color resolution (hardwired 8)
    ch |= (BitsPerPixel - 1);    // OR in the # of bits per pixel
    putByte(p, ch);

    putByte(p, Background);       // background color

    putByte(p, 0);                // future expansion byte

    for (i= 0; i < ColorMapSize; i++)         // Global colormap
    {
        putByte(p, packedColorMap[i][0]);
        putByte(p, packedColorMap[i][1]);
        putByte(p, packedColorMap[i][2]);
    }

    if (comment && strlen(comment) > (size_t) 0)     // write comment blocks
    {
        int   blen;

        putByte(p, 0x21);     // EXTENSION block
        putByte(p, 0xFE);     // comment extension

        blen=strlen(comment);
        if (blen>255) blen = 255;
        putByte(p, blen);
        putNBytes(p, (u8*)comment, blen);
        putByte(p, 0);         // zero-length data subblock to end extension
    }

    putByte(p, ',');            // image separator

    // Write the Image header
    putLSBWord(p, LeftOfs);
    putLSBWord(p, TopOfs);
    putLSBWord(p, Width);
    putLSBWord(p, Height);
    if (Interlace) putByte(p, 0x40);  // Use Global Colormap, maybe Interlace
              else putByte(p, 0x00);

    putByte(p, InitCodeSize);
    compress(p, InitCodeSize+1, b, w*h, pc2nc);

    putByte(p, 0);                    // Write out a Zero-length packet (EOF)
    putByte(p, ';');                  // Write GIF file terminator

    return buffer;
}

// esto es una chapuza
// lo pongo hasta decidir como modelarlo correctamente
#define GIF_EXTENSION ".gif"

bool
gifSaveFile(image_t *img, char *const path, bool addExt)
{
    u8 *dst= NULL;
    int dstLen= img->getWidth() * img->getHeight() * 3 + 4096;
    dst= (u8*)malloc(dstLen);
    int numBytes;

    if (dst == NULL)
    {
        NOTIFY("gifSaveFile: run out of memory\n");
        return false;
    }

    numBytes= gifEncodeFromRGB24(dst,
                                 dstLen,
                                 img->getBuff(),
                                 img->getWidth(),
                                 img->getHeight()
                                );

    if (numBytes <= 0)
    {
        NOTIFY("gifSaveFile: error encoding to GIF, bailing out\n");
        free(dst);
        return false;
    }

    char *fname= (char*)malloc (strlen(path) + strlen (GIF_EXTENSION) + 1);

    if (fname == NULL)
    {
        NOTIFY("gifSaveFile:: run out of memory\n");
        free(dst);
        return false;
    }

    sprintf (fname, "%s%s", path, addExt? GIF_EXTENSION: "");

    int fd;
    if ((fd = open (fname, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
    {
        NOTIFY("gifSaveFile:: ni abrir ficheros\n");
        free (dst);
        free (fname);
        return false;
    }

    write (fd, dst, (size_t)(numBytes));

    close (fd);

    free(dst);
    free(fname);

    return true;
}

