//////////////////////////////////////////////////////////////////////////
// StoreBGI: Now that image is showing, let's store it to file.  If image
//           is larger than 64K, then it is broken up into 5 chunks
//////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#include <graphics.h>
#include "bgi.h"

void StoreBGI (FILE *F, int Width, int Height, char far *VidBuf[5])
{
        int i, yend, yincr, ystart=0;           // bookkeeping vars
        unsigned size;


        size = imagesize(0, 0, Width, Height);  // How big are we talking?

                                                // If image is less than 64K,
                                                // prev. function changes 'size'
                                                // to 0 if image > 64K-1
        if (size != NULLIMAGESIZE)
        {                                       // Alloc space for image
                VidBuf[0] = (char far *) farmalloc((unsigned long) Width * Height);
                                                // read image from screen             
                getimage(0, 0, Width, Height, VidBuf[0]);
                                                // then write it out to file
                fwrite(VidBuf[0], sizeof(char), size, F); 
                farfree(VidBuf[0]);             // And free up memory
        }
        else                                    // image is 64k+, so chunk 
        {                                       // it into fifths
             yincr = (Height+1) / 5;
             yend = yincr;
             size = imagesize(0, ystart, Width, yend);

             for (i=0; i < 5; i++)
             {                                  // Alloc memory
             if ((VidBuf[i] = (char far *) farmalloc((unsigned)size)) == NULL)
             {
                        closegraph();           // Oops, not enough memory
                        printf("StoreBGI> out of memory.  %lu bytes requested\n\n", size);
                        exit(1);
             }
                                                // read in chunk from screen
                getimage(0, ystart, Width, yend, VidBuf[i]);
                                                // and write chunk to file 
                fwrite(VidBuf[i], sizeof(char), size, F);
                farfree(VidBuf[i]);             // then freeing up memory
                ystart = yend + 1;              // advance boundaries of 
                yend += yincr + 1;              // next chunk
             }


        }
}                
         