/*
 * An interface to hash tables for Pan-STARRS
 *
 * Collisions are handled by simple linked lists
 */
#include <stdio.h>
#include "psLib.h"

typedef struct { char *name; } ID;
static ID *IdAlloc(const char *name)
{
    ID *id = psAlloc(sizeof(ID));
    id->name = psStringCopy(name);

    return id;
}

static void IdFree(ID *id)
{
    if (psMemGetRefCounter(id) > 1) {
	psMemDecrRefCounter(id);
	return;
    }

    psFree(id->name);
    psFree(id);
}

int main(void)
{
    psTraceSetLevel("utils.hash", 3);
    long memId0 = psMemGetId();

    psHash *hash = psHashAlloc();

    psHashInsert(hash, "Lynda", IdAlloc("Lee"), (void (*)(void *))IdFree);
    psHashInsert(hash, "Lynda", IdAlloc("Lee"), (void (*)(void *))IdFree);
    psHashInsert(hash, "Robert", IdAlloc("Lupton"), (void (*)(void *))IdFree);
    psHashInsert(hash, "Robert", IdAlloc("the Good"), (void (*)(void *))IdFree);

    char *names[] = {"Robert", "Lynda", "Rowan", NULL};
    for (char **name = names; *name != NULL; name++) {
	ID *id = psHashLookup(hash, *name);
	printf("%s's surname is:\t%s\n", *name,
	       ((id == NULL) ? "(unknown)" : id->name));
    }

    psHashFree(hash, (void (*)(void *))IdFree);
    /*
     * Check for memory leaks
     */
    fprintf(stderr,"Checking for memory leaks:\n");
    psMemCheckLeaks(memId0, NULL, stderr);

    return 0;
}
