#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avgmalloc.h"


int GlobalCount=0,GlobalMax=-1;
int GlobalFirst=-1;
FILE *F;

void *avg_malloc(size_t size, char *s) {
  void *zp;
  GlobalCount+=size; 
  if (GlobalFirst == -1) {
#ifdef TRACE_MALLOC
    F=fopen("malloc.trace","w");
#endif
    GlobalFirst=1;
  }
  if (GlobalCount > GlobalMax) GlobalMax=GlobalCount;
#ifdef TRACE_MALLOC
  fprintf(F,"**MALLOC**  %20s: malloc %8d bytes.Total : %8d \n",s,(int)size,GlobalCount);
  fflush(F);
#endif
  zp=malloc(size);
  if (zp != NULL) { memset(zp,0,size); return(zp); }
   else  {
    fprintf(F," *****SEVERE ***** MALLOC to RETURN NULL STORAGE \n");
    fflush(F);
    return(NULL); 
   }
}

void avg_free(void *ptr,int size,char *s)
{
   free((void *) ptr);
  GlobalCount-=size;
  if (GlobalCount > GlobalMax) GlobalMax=GlobalCount;
#ifdef TRACE_MALLOC
  fprintf(F,"**FREE****  %20s: free   %8d bytes.Left  : %8d Max allocated: %d\n",
          s,(int)size,GlobalCount,GlobalMax);
  fflush(F);
#endif
}

