/* 
----- input.c-------------------------------------------------------- 
 Description: ReadWords: Takes a file and separates all the words from one another, returns the wordcount and an array with all words
     Project: Praktikum Informatik 2
      Author: kobma99134@th-nuernberg.de
        Date: 05-11-2025
------------------------------------------------------------------------- 
*/

#include "input.h"
#include <string.h>
#include <ctype.h>

// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
    // checks, if the file acually exists
    if (file == NULL) {
        return 0;
    }

    //return value: wordcount, as in the number of words that are being read
    int wordcount = 0;
    char readLine[MAX_LINE_LEN];

    // collects the words line by line and adds them to the list, if its not exceeding the max word count
    while (fgets(readLine, sizeof(readLine), file) != NULL && (wordcount < maxWordCount)) {
        
        char word[MAX_WORD_LEN];
        int wordIndex = 0;
        
        //reads every character in the line from start to finish, until the Enter key ('\0')
        for (int i = 0; readLine[i] != '\0'; i++) {
            
            // is the character a letter from the alphabet?
            if(isalpha(readLine[i])) {
                if (wordIndex < MAX_WORD_LEN) {
                    // clean code: We want only uppercase or only lowercase letters to avoid future problems...
                    word[wordIndex++] = toupper(readLine[i]);
                }
            }
            else {
                //if its not a letter, it has to be another character dividing two words e.g. ' ', ',', ';' etc.
                if (wordIndex > 0) {
                    // we want a full word, not an empty string
                    word[wordIndex] = '\0';
                    // add the word to the wordlist
                    strcpy(words[wordcount], word);
                    wordcount++;
                    wordIndex = 0;

                    if (wordcount >= maxWordCount) {
                        return wordcount;
                    }
                }
            }
        }

        //Edge case: If the last word ends on a '\0', right after the last letter
        if (wordIndex > 0 && wordcount < maxWordCount) {
            word[wordIndex] = '\0';
            strcpy(words[wordcount], word);
            wordcount++;
        }

    }
    // regular case: return the total number of words
    return wordcount;
}