//** SUPPORT.C	Simple support functions to load files into memory and do
//**						basic memory allocation.	Used by the DIGPAK & MIDPAK
//**						loader program.  Requires DOSCALLS.ASM and DOSCALLS.H
//**						to do low 1mb memory allocation.
/*																																					 */
/*		Written by John W. Ratcliff (c) 1994																	 */
/*			 Compuserve: 70253,3237 																						 */
/*			 Genie: J.RATCLIFF3 																								 */
/*			 BBS: 1-314-939-0200																								 */
/*			 Addresss:																													 */
/*					 747 Napa Lane																									 */
/*					 St. Charles, MO 63304																					 */
/*																																					 */
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#include "doscalls.h"
#include "keys.h"
#include "support.h"

#define MAXLOWMEM 256 // Maximum number of memory allocations in low-mem.

static char *lowmemloc[MAXLOWMEM];
static short lowmemselect[MAXLOWMEM];
static lowmemcount = 0;

int keystat(void)
{
	return( kbhit() );
}

int getkey(void)
{
	int ch;

	ch = getch();
	if ( ch == 0 ) ch = getch()+256;
	return(ch);
}

char *fload(char *fname,long int *size)
{
	long int fsize;
	char *data=0;
	FILE *fph;

	fph = fopen(fname, "rb");
	if ( fph )
	{
		fseek(fph, 0L, SEEK_END);
		fsize = ftell(fph);
		fseek(fph, 0L, SEEK_SET);
		data = memalloc(fsize);
		if ( data )
		{
			fread(data, fsize, 1, fph);
		}
		fclose(fph);
		*size = fsize;
	}
	return(data);
}


char *floadlow(char *fname,long int *size)
{
	long int fsize;
	char *data=0;
	FILE *fph;

	fph = fopen(fname, "rb");
	if ( fph )
	{
		fseek(fph, 0L, SEEK_END);
		fsize = ftell(fph);
		fseek(fph, 0L, SEEK_SET);
		data = realalloc(fsize);
		if ( data )
		{
			fread(data, fsize, 1, fph);
		}
		fclose(fph);
		*size = fsize;
	}
	return(data);
}

char *memalloc(long int size)
{
	return( malloc( size ) );
}

void memfree(char *mem)
{
	free(mem);
}

char *realalloc(long int size)
{
	char *found=0;

	if ( lowmemcount < MAXLOWMEM )
	{
		found = AllocLowMem(size, &lowmemselect[lowmemcount] );
		if ( found )
		{
			lowmemloc[lowmemcount++] = found;
		}
	}
	return( found );
}

void realfree(char *mem)
{
	int i;

	for (i=0; i<lowmemcount; i++)
	{
		if ( lowmemloc[i] == mem )
		{
			FreeLowMem(lowmemselect[i]); // Free memory by selector.
			lowmemcount--;
			lowmemloc[i] = lowmemloc[lowmemcount]; // move it down.
			lowmemselect[i] = lowmemselect[lowmemcount];
			break;
		}
	}
}
