#include <stdio.h>
#include <stdlib.h>

#ifdef MEMDEBUG
#include "mnemosyne.h"
#endif

#ifdef USE_STACK
static char *base = NULL, *next_free = NULL;
static int allocated = 0;
#define MAX_MEM (512 * 1024 * 1024)

void *claim(int bytes) {
  char *this;
  if (next_free == NULL) next_free = base = malloc(MAX_MEM);
  this = next_free;
  next_free += bytes; allocated += bytes;
  if (allocated > MAX_MEM) {
    fprintf(stderr, "error: insufficient memory available.  Was this a really large image?\n");
    exit(7);
  }
  return this;
}

void release(void *mark) {
  if (mark == NULL) {
    free(base); base = NULL; next_free = NULL; allocated = 0;
    return;
  }
  next_free = (char *)mark;
  allocated = next_free - base;
  if (allocated < 0 || allocated > MAX_MEM) {
    fprintf(stderr, "error: released a pointer that we did not allocate\n");
    exit(8);
  }
}
#else
void *claim(int bytes) {
  void *p = calloc(bytes, 1);
  if (p == NULL) {
    fprintf(stderr, "draw: no memory available\n");
    exit(8);
  }
  return p;
}
void release(void *mark) {
}
#endif