/* Spring 2023 - wordSearch.c

	wordSearch.c 
	the user is asked for a word to see if it is in the text of the file
	then the text from the array is searched and the number of occurrences
	   of the word is printed out to the user

	getting scanf() to work after having used fgets() to read from the file
	is tricky; a Google search for "resetting stdin" helps you find the solution,
	which is shown below on line #20
*/


#include "defs.h"

void searchForWord(char allLines[MAX_LINE][MAX_LINE_LEN], int numLines) {
	int i, j, k = 0, l, found = 0;
	char aWord[50], theWord[50];

	// freopen("/dev/tty", "rw", stdin);  // resets stdin so scanf() will work
	printf("Search the file for what word? \n");
	if (fscanf(stdin, "%s", theWord) == 0)
		printf("nothing entered\n");
	printf(" \"%s\"  appears ", theWord); 

	// get words 
	for (i = 0; i < numLines; i++) {
		for (j = 0; allLines[i][j] != '\n'; j++)  {
			if (isalpha(allLines[i][j]) || isdigit(allLines[i][j])) {  
				aWord[k] = allLines[i][j];  // find the words in the text, one by one
				k++;
			}
			// if get to the end of a word
			if (((allLines[i][j] == ' ') || 
				  (allLines[i][j] == '\n') ||
				  (allLines[i][j] == '-')) && k > 0) {
				// add a null character to the end and strcmp with one searching for
				aWord[k] = '\0';
				// convert each word to all upper case so the search is not case-sensitive
				for (l = 0; aWord[l] != '\0'; l++) {
					if (aWord[l] >= 97 && aWord[l] <= 122)
						aWord[l] = aWord[l] - 32;
				}
				for (l = 0; theWord[l] != '\0'; l++) {
					if (theWord[l] >= 97 && theWord[l] <= 122)
						theWord[l] = theWord[l] - 32;
				} 
				if (strcmp(aWord, theWord) == 0)
					found++;  // keep a count of how many times it was found
				k = 0;
			}
		}
	}

	if (found)
		printf("%d times.\n", found);

}
