/**
 * INCLUDES
 **/
#include <proto/exec.h>
#include <proto/dos.h>

#ifdef MEMTRACE
#include <stdio.h>
#endif

#include <string.h>
#include <pools_protos.h>


/**
 * GLOBALS
 **/
extern void *AmishPool;
extern void *AmishPool2;
extern struct ExecBase *SysBase;


/**
 * LOCAL PROTOTYPES
 **/
static void *__inline MyAllocVec(void *pool, ULONG size);
static void __inline MyFreeVec(void *pool, void *memory);


/**
 * addmemory
 **/
void addmemory(long size)
{
	AmishPool = CreatePool(0, size, size);
}


/**
 * delmemory
 **/
void delmemory(void)
{
	if (AmishPool)
		DeletePool(AmishPool);
	AmishPool = NULL;
}


/**
 * xiMalloc
 **/
char *xiMalloc(unsigned int Size)
{
	return (char *)MyAllocVec(AmishPool, Size);
}


/**
 * xiFree
 **/
void xiFree(void *addr)
{
	if (addr)
		MyFreeVec(AmishPool, addr);
	return;
}


static void *__inline MyAllocVec(void *pool, ULONG size)
{
	UBYTE *memory;

	size += sizeof(ULONG);

	memory = AllocPooled(pool, size);

	if (!memory)
		return NULL;

	*((ULONG *) memory) = size;

	return (void *)(memory + sizeof(ULONG));
}


static void __inline MyFreeVec(void *pool, void *memory)
{
	void *realMemory;
	ULONG size;

	if (!memory)
		return;

	realMemory = (UBYTE *) memory - sizeof(ULONG);
	size = *((ULONG *) realMemory);

	FreePooled(pool, realMemory, size);
}

#ifdef MEMTRACE
FILE *tempfp;
#endif

/**
 * addmemory2
 **/
void addmemory2(long size)
{
#ifdef MEMTRACE
	tempfp = fopen("ram:memtrace", "w");
#endif
	AmishPool2 = CreatePool(0, size, size);
}


/**
 * delmemory2
 **/
void delmemory2(void)
{
	if (AmishPool2)
		DeletePool(AmishPool2);
	AmishPool2 = NULL;
#ifdef MEMTRACE
	fclose(tempfp);
#endif
}

#ifdef MEMTRACE
char *Xalloc(int size, char *file, char *func, int linenum)
#else
char *Xalloc(int size)
#endif
{
#ifdef MEMTRACE
	unsigned long *tmp;
	static unsigned long idnum = 0;

	tmp = (unsigned long *)MyAllocVec(AmishPool2, size+sizeof(unsigned long));
	tmp[0] = idnum++;
	fprintf(tempfp, "%4d calloc   %15s%5d\t%16s\t%lx\t%d\n", tmp[0], file, linenum, func, (unsigned int)tmp+1, size);

	return (char *)(tmp + 1);
#else
	return (char *)MyAllocVec(AmishPool2, size);
#endif
}


#ifdef MEMTRACE
void Xfree(char *p, char *file, char *func, int linenum)
#else
void Xfree(char *p)
#endif
{
#ifdef MEMTRACE
	unsigned long *tmp = NULL;

	if (!p)
		return;

	tmp = ((unsigned long *)p) - 1;
	fprintf(tempfp, "%4d free     %15s%5d\t%16s\t%lx\n", tmp[0], file, linenum, func, (unsigned int)tmp+1);
	MyFreeVec(AmishPool2, (void *)tmp);
#else
	MyFreeVec(AmishPool2, (void *)p);
#endif
	return;
}


