#include <stdio.h>
#include <mem.h>
#include "utype.h"
#include "vmem.h"

static BOOL eof, wasEOF;
static FILE *drawFile = 0;
static long fileStart, fileTop, filePos;
static EXEHEAD fileHeader;
static BYTE inbuffer[2*VMEM_BUFSIZE], *bufferPos;
static int bytesleft;

static BOOL ReadFile(void)
{
	int read;
	eof = ((read = fread(bufferPos+bytesleft, 1, VMEM_BUFSIZE, drawFile))
			!= VMEM_BUFSIZE);
	bytesleft+=read;
	filePos += read;
	return(eof);
}
BYTE *BumpFile(int count)
{
	if (drawFile) {
		bytesleft -= count;
		bufferPos += count;
		if (!eof && (bytesleft < VMEM_BUFSIZE)) {
			memcpy(inbuffer,inbuffer+VMEM_BUFSIZE, VMEM_BUFSIZE);
			bufferPos -= VMEM_BUFSIZE;
			ReadFile();
		}
		if (bytesleft <= 0) {
			if (!wasEOF) {
				wasEOF = TRUE;
				memset(inbuffer, 0, 2*VMEM_BUFSIZE);
			}
			bytesleft = 0;
			bufferPos = inbuffer;
		}
	}
	return(bufferPos);
}
long SeekFile(long position)
{
	if (drawFile) {
		if (position == VMEM_REQUEST)
			return(fileTop);
		bufferPos = inbuffer;
		wasEOF = FALSE;
		if (position >= fileTop) {
			eof = TRUE;
			return(fileTop);
		}
		else {
		     bytesleft = 0;
		     bufferPos = inbuffer;
		     filePos = position;
		     fseek(drawFile, position + fileStart, SEEK_SET);
		     if (ReadFile() || ReadFile())
			return(filePos);
		}
	}
	return(filePos);
}
EXEHEAD * SetFile(char *name)
{
	if (drawFile)
		fclose(drawFile);
	drawFile = 0;
	if (name) {
		fpos_t pos;
		if (!(drawFile = fopen(name,"rb")))
			return((EXEHEAD *) VMEM_NOFILE);
		fseek(drawFile,0L, SEEK_END);
		fileTop = ftell(drawFile);
		fseek(drawFile,0L, SEEK_SET);
		if ((fread(&fileHeader,1, sizeof(EXEHEAD), drawFile)
			!= sizeof(EXEHEAD)) || (fileHeader.ident != EXESIG)) {
			fileStart =0;
		}
		else {
			fileStart = fileHeader.HdrSize << 4;
			fileTop = (fileHeader.PageCnt * 512L) -
				( -fileHeader.PartPag & 511 ) -
				fileStart ;
		}
		SeekFile(0);
	}

	if (!fileStart)
		return(0);

	return(&fileHeader);
}