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

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

#elif defined (SUN) || defined(MSDOS) || 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
{
  UBYTE s_prec;
  UWORD s_iheight;
  UWORD s_iwidth;
  UBYTE s_ccomp;
} SOFBUF;


/*
 *  return JPEG stats of a file
 */

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

{
  int ret;
  struct stat sbuf;
  FILE *fp;
  UBYTE marker[2];
  UWORD length;
  unsigned long llength;
  SOFBUF sofbuf;
  int i, j;

  if (mode)
    {
      ret = lstat (name, &sbuf);
    }
  else
    {
      ret = stat (name, &sbuf);
    }
  if (ret)
    {
      return (-1);
    }
  if ((fp = fopen (name, "rb")) == NULL)
    {
      return (-1);
    }
  if (2L != fread (marker, 1L, 2L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if ((marker[0] != 0xff) || (marker[1] != 0xd8))
    {
      fclose (fp);
      return (-1);
    }
  if (2L != fread (marker, 1L, 2L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if (marker[0] != 0xff)
    {
      fclose (fp);
      return (-1);
    }
  while (marker[1] != 0xc0)
    {
      if (2L != fread (&length, 1L, 2L, fp))
        {
          fclose (fp);
          return (-1);
        }
      llength = (long)(length-2);
      fseek (fp, llength, SEEK_CUR);
      if (2L != fread (marker, 1L, 2L, fp))
        {
          fclose (fp);
          return (-1);
        }
      if (marker[0] != 0xff)
        {
          fclose (fp);
          return (-1);
        }
    }
  if (2L != fread (&length, 1L, 2L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if (1L != fread (&sofbuf, 1L, 1L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if (5L != fread (&(sofbuf.s_iheight), 1L, 5L, fp))
    {
      fclose (fp);
      return (-1);
    }
  if (fclose (fp))
    {
      return (-1);
    }
  buf->p_fsize = sbuf.st_size;
  buf->p_sizex = NSWAP2(sofbuf.s_iwidth);
  buf->p_sizey = NSWAP2(sofbuf.s_iheight);
  buf->p_colrez = sofbuf.s_prec * sofbuf.s_ccomp;
  buf->p_ncol = 1 << buf->p_colrez;
  switch (sofbuf.s_ccomp)
    {
      case 1:
        {
          buf->p_coltype = CT_BW;
          break;
        }
      case 3:
        {
          buf->p_coltype = CT_COLOR;
          break;
        }
      default:
        {
          buf->p_coltype = CT_UNKNOWN;
          break;
        }
    }
  buf->p_nframes = 1;
  buf->p_speed = 0;
  strcpy (buf->p_type, "JFIF");
  return (0);
}
