#include <stdio.h>
#include "config.h"
#include "unixlib.h"

#if defined(ATARI_ST)
#include <string.h>
#include <ext.h>

#elif defined(MSDOS) || defined(SUN) || defined(SEQUENT386) || defined(AVIION)
#include <sys/types.h>
#include <sys/stat.h>

#else
#error Wrong machine type. Edit config.h and follow the instructions.

#endif

#include "portab.h"
#include "picstat.h"


typedef struct
{
  char  s_gifsig[6];
  UWORD s_swidth;
  UWORD s_sheight;
  UBYTE s_sstat;
  UBYTE s_bcolor;
  UBYTE s_res;
  UBYTE s_cmap[768];
} SCREEN_DESC;


#define GLOBL_CMAP(a) ((a) >> 7)
#define COLOR_REZ(a)  ((((a) & 0x70) >> 4) + 1)
#define BIT_PIXEL(a)  (((a) & 0x07) +1)
#define NCOLORS(a)    (1L << BIT_PIXEL(a))


/*
 *  return GIF stats of a file
 */

int gifstat (name, buf, mode)
 char *name;
 struct picstat *buf;
 int mode;

{
  int ret;
  struct stat sbuf;
  FILE *fp;
  SCREEN_DESC sdesc;
  UBYTE *col;
  int i, j;
  int ncols;

  if (mode)
    {
      ret = lstat (name, &sbuf);
    }
  else
    {
      ret = stat (name, &sbuf);
    }
  if (ret)
    {
      return (-1);
    }
  if ((fp = fopen (name, "rb")) == NULL)
    {
      return (-1);
    }
  if (781L != fread (sdesc.s_gifsig, 1L, 781L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if (fclose (fp))
    {
      return (-1);
    }
  if ((strncmp (sdesc.s_gifsig, "GIF87a", 6) != 0) &&
      (strncmp (sdesc.s_gifsig, "GIF89a", 6) != 0))
    {
      return (-1);
    }
  if (GLOBL_CMAP(sdesc.s_sstat) == 0)
    {
      return (-1);
    }
  col = sdesc.s_cmap;
  ncols =NCOLORS(sdesc.s_sstat);

  buf->p_fsize = sbuf.st_size;
  buf->p_sizex = SWAP2(sdesc.s_swidth);
  buf->p_sizey = SWAP2(sdesc.s_sheight);
  buf->p_colrez = COLOR_REZ(sdesc.s_sstat);
  for (buf->p_coltype=CT_BW, i=0; i < ncols; i++)
    {
        if ((col[3*i] != col[3*i+1]) || (col[3*i+1] != col[3*i+2]))
          {
            buf->p_coltype = CT_COLOR;
            break;
          }
      }
  if (buf->p_coltype == CT_COLOR)
    {
      buf->p_colrez *= 3;
    }
  buf->p_ncol = ncols;
  for (i=0; i<ncols; i++)
    {
      for (j=0; j<i; j++)
        {
          if ((col[3*i] == col[3*j]) &&
              (col[3*i+1] == col[3*j+1]) &&
              (col[3*i+2] == col[3*j+2]))
            {
              col[3*j] = col[0];
              col[3*j+1] = col[1];
              col[3*j+2] = col[2];
              buf->p_ncol--;
              break;
            }
        }
    }
  if (buf->p_ncol >= 1<<buf->p_colrez)
    {
      buf->p_ncol = 1<<buf->p_colrez;
    }
  buf->p_nframes = 1;
  buf->p_speed = 0;
  strncpy (buf->p_type, sdesc.s_gifsig, 6);
  buf->p_type[6] = 0;
  buf->p_cols = NULL;
  return (0);
}
