#include <stdio.h>
#include <squarelists.h>

int
compareMyData(int *a, int *b)
{
	return *a > *b ? -1 : *a < *b ? 1 : 0;
}

void
printMyData(FILE *fp, int *a)
{
#if DEBUG
	fprintf(fp, "%08x: %5d\n", a, *a);
#else
	fprintf(fp, "%5d\n", *a);
#endif
}

void
freeMyData(int *a)
{
	free(a);
}

char *x[] = { "30", "40", "20", "10", "80", "70", "90", "100", "110",
		"50", "60", "120", "130", "140", "150", "160", "75", NULL };

main(int argc, char *argv[])
{
	SquareList * root;
	int *a, *b;
	char **p;

	root = SqList_makeHead(compareMyData);
	for(p=x; *p; p++) {
		printf("\n\nx = '%s'\n", *p);
		a = (int *)malloc(sizeof(int));
		*a = atoi(*p);
		printf("insert(%d) => %d\n", *a, SqList_insertNode(&root, a));
	}

	/* find "40" -- this needs to work! */
	a = (int *)malloc(sizeof(int));
	*a = atoi("40");	/* first vert, bottom node */
	printf("findNode(root, %d) = %0x\n",
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\t%d =?= %d\n", *a, *b);
	} else {
		printf("\tERROR: findNode(root, %d) FAILED!\n", *a);
	}
	free(a);

	/* Nuke it .... */
	if (b != NULL) {
		printf("deleteNode(root, %d) = %0x\n",
				*b, (a=(int *)SqList_deleteNode(&root, b)));
		printf("\t%d =?= %d\n", *a, *b);
		*a = 55;
		printf("insert(%d) => %d\n", *a, SqList_insertNode(&root, a));
	}

	a = (int *)malloc(sizeof(int));

	/* This one should fail */
	*a = atoi("5");
	printf("findNode(root,%d) = %0x\n", 
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\tERROR: %d =?= %d\n", *a, *b);
	} else {
		printf("\tFAILED (like it was supposed to)!\n", *a);
	}

	/* This one should work... */
	*a = atoi("80");	/* third vert, top node */
	printf("findNode(root,%d) = %0x\n", 
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\t%d =?= %d\n", *a, *b);
	} else {
		printf("\tERROR: FAILED\n");
	}

	/* This one should work ... fourth vert, middle node */
	*a = atoi("140");
	printf("findNode(root,%d) = %0x\n", 
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\t%d =?= %d\n", *a, *b);
	} else {
		printf("\tERROR: FAILED\n");
	}

	/* This one should work ... fifth vert, only node */
	*a = atoi("160");
	printf("findNode(root,%d) = %0x\n", 
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\t%d =?= %d\n", *a, *b);
	} else {
		printf("\tERROR: FAILED\n");
	}

	/* This one should fail */
	*a = atoi("200");
	printf("findNode(root,%d) = %0x\n", 
			*a, (b = SqList_findNode(&root, a)));
	if (b != NULL) {
		printf("\tERROR: %d =?= %d\n", *a, *b);
	} else {
		printf("\tFAILED (like it was supposed to)!\n");
	}

	free(a);

	a = SqList_getMin(&root);
	printf("MIN: %d\n", *a);
	a = SqList_getMax(&root);
	printf("MAX: %d\n", *a);

	printf("\n===============\n");

	SqList_printList(&root, stdout, printMyData);

	printf("\n===============\n");

	a = SqList_getMin(&root);
	while (a != NULL) {
		printf("Next: %d\n", *a);
		a = SqList_getNext(&root);
	}

	printf("\n===============\n");

	SqList_freeList(&root, freeMyData);
}
