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

int
compareMyData(char *a, char *b)
{
	int rc;

	rc = strcasecmp(a, b);

#if DEBUG
	printf("cmp: %s ?? %s\n\t=> rc=%d\n", a, b, rc > 0 ? -1 : rc < 0 ? 1 : 0 );
#endif
	return rc > 0 ? -1 : rc < 0 ? 1 : 0 ;
}

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

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

char *x[] = { 
	"dc=edu,dc=uvm,ou=Aliases,uvmEduAlias=AIS",
	"dc=edu,dc=uvm,ou=Aliases,uvmEduAlias=BOFH",
	"dc=edu,dc=uvm,ou=Aliases,uvmEduAlias=LINUXGEEK",
	"dc=edu,dc=uvm,ou=Aliases,uvmEduAlias=virus",
	"dc=edu,dc=uvm,ou=People,netid=atb",
	"dc=edu,dc=uvm,ou=People,netid=kdk",
	"dc=edu,dc=uvm,ou=People,netid=mga",
	"dc=edu,dc=uvm,ou=People,netid=fcs",
	"dc=edu,dc=uvm,ou=Aliases,cn=\"Swasey, Francis\"",
	NULL };

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

	root = SqList_makeHead(compareMyData);
	for(p=x; *p; p++) {
		printf("\n\nx = '%s'\n", *p);
		a = strdup(*p);
		printf("insert(%s) => %d\n", a, SqList_insertNode(&root, a));
		SqList_printList(&root, stdout, printMyData);
		printf("\n******\n");
	}

	a = strdup("dc=edu,dc=uvm,ou=People,netid=fcs");
	printf("findNode: %s\n", a);
	b = SqList_findNode(&root, a);
	printf("%s =?= %s\n", a, b);
	free(a);
	if ( b != NULL ) {
		printf("deleteNode: %s\n", b);
		a = (char *)SqList_deleteNode(&root, b);
		printf("%s =?= %s\n", a, b);
		if ( a != NULL ) {
			free(a);
		} else {
			printf("deleteNode failed!\n");
		}
		free(b);
		SqList_printList(&root, stdout, printMyData);
		printf("\n******\n");
	} else {
		printf("findNode failed!\n");
	}

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

	SqList_printList(&root, stdout, printMyData);

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

	printf("The maximum is:\n");
	a = SqList_getMax(&root);
	printMyData(stdout, a);

	printf("The minimum is:\n");
	a = SqList_getMin(&root);
	printMyData(stdout, a);

	printf("Deleting the minimum:\n");
	b = SqList_deleteNode(&root, a);
	printf("done.\nDeleted Node is:");
	printMyData(stdout, b);

	printf("Wiping out SquareList\n");
	SqList_freeList(&root, freeMyData);

	printf("Building testcase of deleting only node\n");
	root = SqList_makeHead(compareMyData);
	printf("insert(%s) => %d\n", a, SqList_insertNode(&root, a));
	SqList_printList(&root, stdout, printMyData);
	printf("\n******\n");

	printf("The minimum is:\n");
	a = SqList_getMin(&root);
	printMyData(stdout, a);

	printf("Deleting the minimum (and only node)\n");
	b = SqList_deleteNode(&root, a);
	printf("\tdone.\nDeleted Node is:");
	printMyData(stdout, b);

	if ( root != NULL ) {
		printf("ERROR: root should be null!\n");
	} else {
		printf("SUCCESS: root is null!\n");
	}

	return 0;
}
