#include <stdio.h>
#include <sys/time.h>
#include "dict.h"

int IntCmp(const void *a, const void *b)
{
	return *(const int *)a - *(const int *)b;
}

#define TEST_SIZE 3000000
#define RAND_RANGE 5000

void printtime(struct timeval *a,struct timeval *z)
{
	struct timeval e;
	timersub(z, a, &e);
	printf("Elapsed: %lds %ldus\n", e.tv_sec, e.tv_usec);
}

int main(int argc, char *argv[])
{
	dict_t *d;
	dnode_t *dn,*dd;
	int i;
	int max = 2147483647;
	int values[TEST_SIZE];
	dnode_t *nodes; // [TEST_SIZE];
	int x;
	struct timeval a,z;

	nodes = (dnode_t *)malloc(sizeof(dnode_t) * TEST_SIZE);

	for (x = 0; x < 4; x++)
	{
		d = dict_create(TEST_SIZE + 1, IntCmp);
		dict_allow_dupes(d);

		printf("Create...\n");
		gettimeofday(&a,NULL);
		for (i=0; i < TEST_SIZE; i++)
		{
//			if (i % 10000 == 0)
//			{
//				printf("%d: ", i);
//				gettimeofday(&z,NULL);
//				printtime(&a,&z);
//			}
			values[i] = random() % RAND_RANGE;
//			values[i] = i;
	//		dn = dnode_create(values + i);
			dnode_init(&nodes[i], values + i);
			// dn->dict_key = values + i;
			dict_insert(d, &nodes[i], values + i);
		}
		gettimeofday(&z,NULL);
		printtime(&a,&z);

		printf("Walk...\n");
		gettimeofday(&a,NULL);
		i = 0;
		dn = dict_first(d);
		do {
//			if (values[i] != *(int *)dn->dict_key)
//				printf("Mismatch! %d != %d\n", i, *(int *)dn->dict_key);
			i++;

			dd = dn;
			dn = dict_next(d, dn);
		} while (dn);

		if (i != TEST_SIZE)
			printf("Walked %d values, expected %d\n", i, TEST_SIZE);
		gettimeofday(&z,NULL);
		printtime(&a,&z);

		printf("Destroy...\n");
		gettimeofday(&a,NULL);
//		dict_free_nodes(d);
		d->dict_nodecount = 0; // HAX!
		dict_destroy(d);
		gettimeofday(&z,NULL);
		printtime(&a,&z);
	}

	return 0;
}

