#include "all.h"
#ifndef __TURBOC__
#define farcalloc calloc
#else
#include <alloc.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 alocate save memory\n");
}
static long totalmem,worst;
void myfree(void *p)
{
	myfrees(p,"UNKNOWN");
}
void myfrees(void *p,char *s)
{
	static long *l;
	l = 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(long nitems,long size)
{
	return myallocz(nitems*size);
}
void *myalloc(long size)
{
	static void *p;
	static long *l;
	if (size==0) {
		sprintf(errgle," error, attempt to allocate ZERO memory \n");
		gle_abort(errgle);
	}
	if (size>40000) gprint(" allocating alot of memory %d \n",size);
	p = malloc(size+8);
	if (p==NULL) {
		freeafont();
		p = malloc(size+8);
		if (p==NULL) {
		 free_savemem();
		 sprintf(errgle,"\n Memory allocation failure (size %d)  \n"
			,size);
		 gle_abort(errgle);
		}
	}
	l = p;
	*l++ = 1234;
	*l = size+8;
	totalmem += *l;
	if (totalmem>worst) worst = totalmem;
	p = ++l;
	return p;
}
void *myallocz(long size)
{
	static void *p;
	static long *l;
	if (size==0) {
		free_savemem();
		sprintf(errgle," zerror, attempt to allocate ZERO memory \n");
		gle_abort(errgle);
	}
	if (size>40000) {
	  gprint(" zallocating alot of memory %ld \n",size);
	}
	p = farcalloc(1,size+8);
	if (p==NULL) {
	   freeafont();
	   p = farcalloc(1,size+8);
/* 	   if (p==NULL) {
		free_cache();
		gprint("Freeing cached characters\n");
		p = farcalloc(1,size+8);
	   }
*/
	   if (p==NULL) {
		free_savemem();
		sprintf(errgle,"\n\n zMemory allocation failure %d  \n\n"
			,size);
		gle_abort(errgle);
	   }
	}
	l = p;
	*l++ = 1234;
	*l = size+8;
	totalmem += *l;
	if (totalmem>worst) worst = totalmem;
	p = ++l;
	return p;
}
long mem_total()
{
	return totalmem;
}
long mem_worst()
{
	return worst;
}

long gtotalmem;
/*
#include <alloc.h>
void far * far _graphgetmem(unsigned size)
{
	gtotalmem += size;
	totalmem += size;
	return(farmalloc(size));
}
void far _graphfreemem(void far *ptr, unsigned size)
{
	totalmem -= size;
	gtotalmem -= size;
	farfree(ptr);
}


*/

