#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <proto/exec.h>
#include <proto/intuition.h>
#include "display.h"

char *name;

char *bufor;

static int   GetByte(FILE *fp);
static int   GetWord(FILE *fp);
static void  readImage(FILE *fp, unsigned char *buf, int BytesPerLine, int Height);
/*static void  showImage(unsigned char *buf, int Width, int Height);*/

static int GetByte(fp)
FILE *fp;
{
   int c;

   if((c=getc(fp))==EOF)
      assert(c!=EOF);
   return c;
}

static int GetWord(fp)
FILE *fp;
{
   int c;

   c=GetByte(fp);
   c|=(GetByte(fp)<<8);
   return c;
}

static void  readImage(fp, buf, BytesPerLine, Height)
FILE *fp;
unsigned char *buf;
int BytesPerLine;
int Height;
{
   int           c;
   int           nbytes;
   int           count;

   nbytes=BytesPerLine*Height;

   while(nbytes>0)
   {
      c=GetByte(fp);
      if((c&0xc0)!=0xc0)
      {
         *buf++=c;
         --nbytes;
         continue;
      }
      count=c&0x3f;
      c=GetByte(fp);
      assert(count<=nbytes);

      nbytes-=count;
      while(--count>=0)
         *buf++=c;
   }
}

void main(int argc, char *argv[])
{
   register int  i;
   FILE          *ifp;
   int           Version;
   int           Xmin, Xmax, Ymin, Ymax;
   int           Width, Height;
   int           Planes, BitsPerPixel, BytesPerLine, tmp;
   unsigned char red[256], green[256], blue[256], gray[256];
   unsigned char *data;

   name=argv[1];

   bufor=(unsigned char *)malloc(16384);

   if(ifp=fopen(name, "rb"))
   {
      if(bufor) setvbuf(ifp, bufor, _IOFBF, 16384);
      if(GetByte(ifp)!=0x0a)
         assert(0);
      Version=GetByte(ifp);
      tmp=GetByte(ifp);
      assert(tmp==1);
      BitsPerPixel=GetByte(ifp);
      assert(BitsPerPixel==8);

      Xmin=GetWord(ifp);
      Ymin=GetWord(ifp);
      Xmax=GetWord(ifp);
      Ymax=GetWord(ifp);

      Width=(Xmax-Xmin)+1;
      Height=(Ymax-Ymin)+1;

      (void) GetWord(ifp);
      (void) GetWord(ifp);

      for(i=0;i<16;i++)
      {
         red[i]=GetByte(ifp);
         green[i]=GetByte(ifp);
         blue[i]=GetByte(ifp);
      }

      (void) GetByte(ifp);
      Planes=GetByte(ifp);
      BytesPerLine=GetWord(ifp);
      (void) GetWord(ifp);

      fseek(ifp, (long)128, 0);

      data=(unsigned char *)malloc(BytesPerLine*Height);
      
      if(data)
      {
         readImage(ifp, data, BytesPerLine, Height);
   
         (void) GetByte(ifp);
         for(i=0;i<256;i++)
         {
            red[i]=GetByte(ifp);
            green[i]=GetByte(ifp);
            blue[i]=GetByte(ifp);
            gray[i]=(299*red[i]+587*green[i]+114*blue[i])/16000;
         }
      }
      fclose(ifp);
      if(data) showImage(data, gray, BytesPerLine-1, Height);
      if(data) free(data);
      if(bufor) free(bufor);
   }
}
