#include <stdio.h>
#include <graphics.h>
#include <alloc.h>
#include "bgi.h"

extern BGIPREFACE BGIHeader;                    // Header stuff for the BGI
                                                // files created w/ BMP2BGI

void ShowBGI (FILE *f, char far *VidBuf[5])
{
  int ystart=0, yend, yincr, i;                 // var's for processing BGI images >= 64k
  unsigned size;
                                                
  setallpalette(&BGIHeader.palette);            // Set the screen palette

                                                // Just how big are we talking?
  size = imagesize(0, 0, BGIHeader.Width, BGIHeader.Height);


                                                // Reset File pointer to where
                                                // the image resides
  fseek(f, BGIHeader.Foffset, SEEK_SET);

                                                // if image is less than 64k-1
                                                // bytes, read it all in at once
  if (size != NULLIMAGESIZE)
  {
                                                // Alloc space for image
        VidBuf[0] = (char far *) farmalloc((unsigned long) size);
                                                // Read in image     
        fread(VidBuf[0], sizeof(char), size, f);
        putimage(0, 0, VidBuf[0], COPY_PUT);    // & Display the image
        farfree(VidBuf[0]);                     // Free up allocated space
  }
  else                                          // if image is >= 64k, gotta 
  {                                             // fetch & display in chunks
        yincr = (BGIHeader.Height+1) / 5;       // large images are stored in fifths
        yend = yincr;                           // track end of chunk
        size = imagesize(0,ystart,BGIHeader.Width,yend);
             
        for (i=0; i < 5; i++)
        {
                if ((VidBuf[i] = (char far *) farmalloc((unsigned long) size)) == NULL)
                {
                                                // Can't display: No memory for image
                        closegraph();
                        printf("ShowBGI> Out of heap space.\n");
                        printf("ShowBGI> Press any key to abort");
                        getch();
                        exit(12);
                }
                                                // Read in i-th chunk
                fread(VidBuf[i], sizeof(char), size, f);
                                                // and display the chunk
                putimage(0, ystart, VidBuf[i], COPY_PUT);
                farfree(VidBuf[i]);             // free up some memory
                ystart = yend + 1;              // advance boundaries for
                yend += yincr + 1;              // next chunk   
        }


  }
}