#include "all.h"
#ifndef __TURBOC__
#define farcalloc calloc
#else
#include <alloc.h>
#endif
#ifdef unix
#include <malloc.h>
#endif
extern char errgle[];
int free_savemem(void);
char *sdup(char *s)
{
	char *v;
	v = myalloc(strlen(s)+1);
	strcpy(v,s);
	return v;
}
char *save_memory;
free_savemem()
{
	if (save_memory!=NULL) free(save_memory);
	save_memory = 0;
}
init_memory()
{
    save_memory = malloc(1000);
    if (save_memory == NULL) gle_abort("Not able to allocate save memory\n");
}
static int32 totalmem,worst;
void myfree(void *p)
{
	myfrees(p,"UNKNOWN");
}
void myfrees(void *p,char *s)
{
	static int32 *l;


	l = (int32 *) p;
	totalmem -= *(--l);
	if (*(--l)!=1234) {
		sprintf(errgle,"Free memory (%s) not mine %ld  %ld \n",s,*l,*(++l));
		gle_abort(errgle);
	}
	free(l);
	return;
}
void *myallocn(int32 nitems,int32 size)
{
	return myallocz(nitems*size);
}

void *myalloc(int32 size)
{
	static void *p;
	static int32 *l;

	if (size==0) {
		sprintf(errgle," error, attempt to allocate ZERO memory \n");
		gle_abort(errgle);
	}
	if (size>40000) gprint(" allocating a lot of memory %d \n",size);
	p = malloc(size+sizeof(int32)*2);
	if (p==NULL) {
		freeafont();
		p = malloc(size+sizeof(int32)*2);
		if (p==NULL) {
		 free_savemem();
		 sprintf(errgle,"\n Memory allocation failure (size %d)  \n"
			,size);
		 gle_abort(errgle);
		}
	}
	l = (int32 *) p;
	*l++ = 1234;
	*l = size+sizeof(int32)*2;
	totalmem += *l;
	if (totalmem>worst) worst = totalmem;
	p = (void *) ++l;

	return p;
}
void *myallocz(int32 size)
{
	static void *p;
	static int32 *l;
	if (size==0) {
		free_savemem();
		sprintf(errgle," zerror, attempt to allocate ZERO memory \n");
		gle_abort(errgle);
	}
	if (size>40000) {
	  gprint("(z) allocating a lot of memory %ld \n",size);
	}
	p = farcalloc(1,size+sizeof(int32)*2);
/*	p = farcalloc((size+8)/4,4);*/
	if (p==NULL) {
	   freeafont();
	   p = farcalloc(1,size+sizeof(int32)*2);
/* 	   if (p==NULL) {
		free_cache();
		gprint("Freeing cached characters\n");
		p = farcalloc(1,size+sizeof(int32)*2);
	   }
*/
	   if (p==NULL) {
		free_savemem();
		sprintf(errgle,"\n\n (z) Memory allocation failure %d  \n\n"
			,size);
		gle_abort(errgle);
	   }
	}
	l = (int32 *) p;
	*l++ = 1234;
	*l = size+sizeof(int32)*2;
	totalmem += *l;
	if (totalmem>worst) worst = totalmem;
	p = (void *) ++l;
	return p;
}
int32 mem_total()
{
	return totalmem;
}
int32 mem_worst()
{
	return worst;
}

int32 gtotalmem;
#ifdef __TURBOC__
#include <alloc.h>
void far * far _graphgetmem(unsigned size)
{
	return(myalloc(size));
}
void far _graphfreemem(void far *ptr, unsigned size)
{
	myfree(ptr);
}

#endif

