#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include "psLib.h"

static long my_MemAllocateCB(const psMemBlock *ptr)
{
    static int n = 1;			// "p_psMemAllocateID += n"

    assert (ptr != NULL);		// prevent compiler warnings
    
    if(psMemCheckCorruption(0)) {
	psError(__func__, PS_ERR_MEMORY_CORRUPTION, PS_NEW_ERROR, "Detected corrupted memory\n");
    }
    
    return n;				// see every nth allocation
}

int main(void)
{
    psLogSetFormat("NM");		// suppress some of the psLogMsg verbosity

    (void)psMemAllocateCBSet(my_MemAllocateCB);
    //(void)psMemFreeCBSet(my_MemAllocateCB);
    psMemAllocateIDSet(1);
    psMemFreeIDSet(14);
    
#if 0
    psTraceSetLevel("", 10);
#else
    psTraceSetLevel("utils.dlist.add.head", 9);
    psTraceSetLevel("utils.dlist.add", 3);
    psTraceSetLevel("utils.dlist.remove", 4);
    psTraceSetLevel("coadd", 2);
    psTraceSetLevel("coadd.CR.remove.morphology", 5);
    psTraceSetLevel("utils.hash", 2);
    psTraceSetLevel("utils.dlist.add", 9);
    psTraceSetLevel("utils", 1);
#endif
    
    psTracePrintLevels();
    printf("\n");

    psTrace("utils.dlist.remove", 2, "Removing psDList key \"%s\"\n", "my_key");
    psTrace("utils", 2, "Initialising utilities library\n");
    psTrace("", 2, "This is turned on by trace component \"\"");
    psTrace("utils.dlist", 2, "Initialising psDList\n");
    psTrace("utils.dlist.remove", 4, "Removing psDList key \"%s\" (value: \"%d\")\n", "my_key", 12345);
    psTrace("utils.hash.remove", 4, "Removing hash key \"%s\" (value: \"%d\")\n", "my_key", 12345);
    psTrace("utils.dlist.add", 1, "Adding psDList key \"%s\"\n", "your_key");
    psTrace("utils.dlist.find", 2, "Looking up psDList key \"%s\"\n", "some_key");
    psTrace("coadd.CR.remove", 4, "Removing CRs\n");
    psTrace("coadd.CR.remove.morphology", 4, "CRs are not fuzzy\n");

    psTraceReset();
    fprintf(stderr,"\n");
    fprintf(stderr,"Checking for memory leaks:\n");
    psMemCheckLeaks(0, NULL, stderr);
    

    return 0;
}
