#include "gp_alloc.h"
/* #include "gp_graph3d.h" */
#include <math.h>
#define TRACE_ALLOC(x)	
struct frame_struct {
    char *use;
    int requested_size;
    int pad;			/* preserve 8-byte alignment */
    int checksum;
};
 
#define CHECKSUM_INT 0xcaac5e1f
#define RESERVED_SIZE sizeof(struct frame_struct)
#define CHECKSUM_CHAR 0xc5

static long bytes_allocated = 0;

static void
mark(p, size, usage)
struct frame_struct *p;
unsigned long size;
char *usage;
{
    p->use = usage;
    p->requested_size = size;
    p->checksum = (CHECKSUM_INT ^ (int) (p->use) ^ size);
    ((unsigned char *) (p + 1))[size] = CHECKSUM_CHAR;
}

void *
gp_alloc(size, usage)
size_t size;
const char *usage;
{
    struct frame_struct *p;
    size_t total_size = size + RESERVED_SIZE + 1;

    /*TRACE_ALLOC(("gp_alloc %d for %s\n", (int) size, usage ? usage : "<unknown>"));*/
    /*printf("gp_alloc %d for %s\n", (int) total_size, usage ? usage : "<unknown>");*/
    p = malloc(total_size);
    if (!p){ printf("gp_alloc :  Out of memory !!!! \n"); exit(-99);}
    /*int_error(NO_CARET, "Out of memory");*/

    bytes_allocated += size;

    /*mark(p, size, usage);*/

    /*return (char *) (p+1);*/
    return (char *) (p);
}
 
void gp_free(void *p){
  free(p);
}

void contour_free(struct gnuplot_contours *ptr){
  //char *c;
  struct coordinate *coords;
  struct gnuplot_contours *old;
  struct gnuplot_contours *cur;
 
  cur = ptr; 
  //printf("\n contour_free  %x \n",cur);
  while(cur){
    /*printf(" contour_free  %x \n",cur);*/
    old = cur;
    cur = cur->next;    
    coords = old->coords;    
    if(coords){free(coords) ; coords = NULL;}
    free(old);    
    old=NULL;
  } 
  

}
/*
 * iso_alloc() allocates a iso_curve structure that can hold 'num'
 * points.
 */
struct iso_curve *
iso_alloc(num)
int num;
{
    struct iso_curve *ip;
    ip = (struct iso_curve *) gp_alloc(sizeof(struct iso_curve), "iso curve");
    ip->p_max = (num >= 0 ? num : 0);
    if (num > 0) {
	ip->points = (struct coordinate  *)
	    gp_alloc(num * sizeof(struct coordinate), "iso curve points");
    } else
	ip->points = (struct coordinate  *) NULL;
    ip->next = NULL;
    return (ip);
}
/*
 * iso_free() releases any memory which was previously malloc()'d to hold
 *   iso curve points.
 */
void iso_free(struct iso_curve *ip)
{
    if (ip) {
        if (ip->points)
            free((char *) ip->points);
        free((char *) ip);
    }
}
