#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "tmalloc.h"

struct memlist {
    int obj;
    void *ptr;
    struct memlist *next;
} *mem_list=NULL, *eomem_list=NULL;

#ifdef DEBUG
void *
tmalloc(n, id)
int n;
int id;
{
    struct memlist *ml;
    char *mem;

    ml = malloc(sizeof(struct memlist));
    if (ml == NULL) {
	fprintf(stderr, "Out of memory\n");
	exit(1);
    }
    mem = (char *)malloc(n);
    if (mem == NULL) {
	fprintf(stderr, "Out of memory\n");
	exit(1);
    }
    ml->obj = id;
    ml->next = NULL;
    ml->ptr = mem;
    if (eomem_list) {
	eomem_list->next = ml;
    } else {
	mem_list = ml;
    }
    eomem_list = ml;
    return(mem);
}
#else
#pragma warn -par
void *tmalloc(n, id)
int n;
int id;
{
    char *mem;

    mem = (char *)malloc(n);
    if (mem == NULL) {
	fprintf(stderr, "Out of memory\n");
	exit(1);
    }
    return(mem);
}
#pragma warn .par
#endif

#ifdef DEBUG
void tfree(void *mem)
{
    struct memlist *ml, *pml=NULL;

    for (ml=mem_list; ml != NULL; pml = ml, ml = ml->next) {
	if (ml->ptr == mem) {
	    if (pml == NULL) {
		mem_list = ml->next;
		if (ml == eomem_list) eomem_list=NULL;
	    } else {
		pml->next = ml->next;
		if (ml == eomem_list) eomem_list=pml;
	    }
	    free(ml);
	    break;
	}
    }
    if (ml == NULL) {
	printf("Trying to kill this more than once: %08lx\n", mem);
    } else {
	free(mem);
    }
}
#else
void tfree(void *mem)
{
    free(mem);
}
#endif

#ifdef DEBUG
void tdebug()
{
    struct memlist *ml;

    printf("-----\n");
    for (ml=mem_list; ml != NULL; ml = ml->next) {
	printf("object %lx: %d\n", ml->ptr, ml->obj);
	fflush(stdout);
    }
    fflush(stdout);
}
#endif
