/* 
 * Test program for WordMap (Homework 1X, part 2)
 *
 * This is some very messy code.  Read at your own peril.
 *
 * Add more test cases if you wish
 */

/*
 * In this program, words are mapped to words.
 * That way we don't have to worry about having a working MapLoop
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "WordMap.h"

/*
 *
 * A small collection of tests...
 */
WordMap littleTest(void) {
    WordMap testMap ;
    char *testRes ;
    int failed = 0 ;
    
    testMap = CreateWM() ;
    if (testMap == NULL) {
        puts("Failure @") ;
        return NULL ;
    }
    InsertWM(testMap, "NCSU",  (void *)"Raleigh") ;
    InsertWM(testMap, "UNCA",  (void *)"Asheville") ;
    InsertWM(testMap, "UNC-W", (void *)"Wilmington") ;
    
    testRes = (char *)LookupWM(testMap, "UNCA") ;
    if (testRes == NULL) {
        puts("Failure A1") ;
	failed = 1 ;
    } else if (strcmp(testRes , "Asheville")) {
        puts("Failure A2") ;
	failed = 1 ;
    }

    testRes = (char *)LookupWM(testMap, "NCSU") ;
    if (testRes == NULL) {
        puts("Failure B1") ;
	failed = 1 ;
    } else if (strcmp(testRes , "Raleigh")) {
        puts("Failure B2") ;
	failed = 1 ;
    }

    testRes = (char *)LookupWM(testMap, "UNC-W") ;
    if (testRes == NULL) {
        puts("Failure C1") ;
	failed = 1 ;
    } else if (strcmp(testRes, "Wilmington")) {
        puts("Failure C2") ;
	failed = 1 ;
    }
    if (failed) {
        return NULL ;
    } else {
        return testMap ;
    }
}

/*
 *
 * A  bigger collection of tests...
 */
WordMap bigTest(void) {
    int i ;
    WordMap testMap ;
    char valBuff[1000][20] ;
    char *value ;

    testMap = CreateWM() ;

    for (i=0; i<1000; ++i) {
        sprintf(valBuff[i], "W%04dXYZ", i) ;
        if (InsertWM(testMap, valBuff[i], (void *)valBuff[i])) {
            printf("Problem inserting %s\n", valBuff[i]) ;
	    return(NULL) ;
	}
    }
    for (i=0; i<1000; ++i) {
        value = (char *)LookupWM(testMap, valBuff[i]) ;
	if (strcmp(valBuff[i],value)) {
            printf("Problem with %s->%s\n", valBuff[i], value) ;
	    return NULL ;
	}
    }
    return testMap ;
}

#define TOTALRUNS 300000
#define PRINTINFO  30000

/*
 *
 * A ridiculous collection of tests
 * Calls bigTest 1,000,000 times
 */
void testDestroy(int destroy) {
    int i ;
    for (i=0; i<TOTALRUNS; ++i) {
        if (i%PRINTINFO==0) {
            printf("%6d\n", i) ;
        }
        WordMap w = bigTest() ;
	if (w == NULL) {
            printf("Failed on %d'th run of bigTest\n", i) ;
            return ;
	}
        if (destroy) DestroyWM(w) ;
    }
}

int main(int argc, char** argv) {

    puts("Little test") ;
    if (littleTest() == NULL) 
        return EXIT_FAILURE ;

    puts("Big test") ;
    if (bigTest() == NULL)
        return EXIT_FAILURE ;

    puts("Testing with destroy on") ;
    testDestroy(1) ;
    puts("Testing with destroy off") ;
    testDestroy(0) ;

    return (EXIT_SUCCESS);
}

