/*                      QBCC Project

This source file is licensed under the GNU Lesser Public Licence which should be 
included with the distribution of this source.

*/
// Memory Allocation functions (for strings)

#include "../include/stdlibh.h"
#include "../include/stringh.h"


unsigned char *MemBlock;

int Block_Limit = 0;
int Block_Current = 0;
int Allocated = FALSE;

///////////////////
// Allocate the main block
int AllocateMemBlock(int NumBytes)
{
	MemBlock = (unsigned char *)malloc(sizeof(unsigned char) * NumBytes);
	if(MemBlock == NULL)
	{
		fprintf(stderr,"Error: Not enough memory to allocate the mem heap!\n");
		return FALSE;
	}

	Block_Limit = NumBytes;
	Allocated = TRUE;
	return TRUE;
}


///////////////////
// Fee the main block
void FreeMemBlock(void)
{
	if(MemBlock)
		free(MemBlock);
	Allocated = FALSE;
	Block_Limit = 0;
}






// NOTE: Don't call below for strings, use 'NewPTRString', coz that allocates a string specially

///////////////////
// Returns a pointer
void *GetPointer(size_t size)
{
	if(Block_Current == Block_Limit)
	{
		fprintf(stderr,"Error: Out of memory heap space!\n");
		return NULL;
	}

	if(!Allocated)
	{
		fprintf(stderr,"Error: Memory heap not allocated!\n");
		return NULL;
	}

	Block_Current += size;
	return MemBlock + (Block_Current - size);
}






// NOTE: Below we don't cover strings because strVcpy handles that

///////////////////
// Converts a INTEGER value to a pointer
/*__inline*/ int *GetINTptr(int value)
{
	int *ptr = (int *)GetPointer(sizeof(int));
	*ptr = value;
	return ptr;
}

///////////////////
// Converts a SINGLE value to a pointer
/*__inline*/ float *GetSNGptr(float value)
{
	float *ptr = (float *)GetPointer(sizeof(float));
	*ptr = value;
	return ptr;
}

///////////////////
// Converts a LONG value to a pointer
/*__inline*/ long *GetLNGptr(long value)
{
	long *ptr = (long *)GetPointer(sizeof(long));
	*ptr = value;
	return ptr;
}

///////////////////
// Converts a DOUBLE value to a pointer
/*__inline*/ double *GetDBLptr(double value)
{
	double *ptr = (double *)GetPointer(sizeof(double));
	*ptr = value;
	return ptr;
}