#include "kwic.h" #include "noise_word_storage.h" #define MAX_WORDS 3 static char **word_list; static int word_list_length; static int num_words; /* internal state invariant * 1. word_list[0..word_list_length-1] is allocated * 2. word_list[0..num_words-1] contains pointers to null-terminated C strings * 3. word_list[0..num_words-1] is sorted in ascending order */ /** @purpose Initialize the module. Return the appropriate KWIC status code. @preconditions none */ int ns_init(void) { // create an empty word_list with default space word_list_length = MAX_WORDS; num_words = 0; word_list = calloc(word_list_length,sizeof(char *)); if (word_list == NULL) { return KW_MEMORY_ERROR; } else { return KW_SUCCESS; } } /** @purpose Add word to the currently stored list of words. if not enough memory is available to store word return KW_MEMORY_ERROR else return KW_SUCCESS @preconditions word is a legal C string ns_init has been called and returned KW_SUCCESS */ int ns_add_word(char *word) { int insert_position,i,n; // if word_list is full, double its size if (num_words >= word_list_length) { word_list_length *= 2; word_list = realloc(word_list, word_list_length*sizeof(char*)); if (word_list == NULL) { return KW_MEMORY_ERROR; } } printf("%d %d\n",word_list_length,num_words); // find position to insert word for (insert_position = 0; insert_position < num_words; insert_position++) { printf("%d\n",insert_position); n = strcasecmp(word,word_list[insert_position]); if (n == 0) { // already in word_list: ignore return KW_SUCCESS; } else if (n < 0) { // insert position found break; } } // shift word_list[i..num_words-1] to the right num_words++; for (i = num_words-1; i > insert_position; i--) { printf("%d\n",i); word_list[i] = word_list[i-1]; } // insert word in place word_list[insert_position] = malloc(strlen(word)+1); if (word_list[insert_position] == NULL) { return KW_MEMORY_ERROR; } strcpy(word_list[insert_position],word); return KW_SUCCESS; } /** @purpose Return 1 if word is in the currently stored list and 0 otherwise. When searching, the comparisons must be case insensitive. For example, "aaa" and "aAa" are considered equal. @preconditions word is a legal C string ns_init has been called and returned KW_SUCCESS */ int ns_find_word(const char *word) { int high,low,mid,compare; low = 0; high = num_words - 1; while (low <= high) { mid = (low+high)/2; printf("%d %d %d\n",low,mid,high); compare = strcasecmp(word,word_list[mid]); if (compare < 0) high = mid-1; else if (compare == 0) return 1; else low = mid+1; } return 0; }