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


// TODO:
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.

/*
char *readSingleWord(FILE *file)
{
    if (file == NULL)
    {
        return 0;
    }
    

    fgets(singleWordBuffer, MAX_LINE_LEN, file);
    
}
*/


// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
    int     currentlyInWord     = 0;
    int     word                = 0;
    int     wordChar            = 0;
    char    currentChar         = 0;


    do
    {
        // get the next char from the file
        currentChar = fgetc(file);
    
        // if current char is a capital letter 
        // write it into the words array
        if ((currentChar >= 'A') && (currentChar <= 'Z'))
        {
            if (!currentlyInWord)
            {
                currentlyInWord = 1;
            }
                
            words[word][wordChar] = currentChar;
            wordChar++;
        }
        // if the current char is a lowercase letter
        // change it to its capital version
        // and write it into the words array
        else if ((currentChar >= 'a') && (currentChar <= 'z'))
        {
            if (!currentlyInWord)
            {
                currentlyInWord = 1;
            }

            words[word][wordChar] = toupper(currentChar);
            wordChar++;
        }
        // if the current char is NOT a letter
        // the end of a word has been reached
        // skip chars untill a new letter is found
        else if (currentlyInWord)
        { 
            words[word][wordChar] = '\0';
            word++;
            wordChar        = 0;
            currentlyInWord = 0;
        }

    } while (((currentChar != EOF) && (word <= maxWordCount)));

    return word;
}



/*
#define MAX_BUFFER_LEN 256

// TODO?
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.

// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
    char buffer[MAX_BUFFER_LEN];
    int count = 0;
    char *teiler = ".,; !?\n";

    if(file == NULL)
    {
        printf("Fehler beim Öffnen von words.txt!\n");
        return -1;
    }

    while(fgets(buffer, MAX_LINE_LEN, file))
    {
        const char *wort = strtok(buffer, teiler);

        while(wort != NULL && count < maxWordCount)
        {
            strncpy(words[count], wort, MAX_WORD_LEN-1);
            words[count][MAX_WORD_LEN-1] = '\0';
            count++;

            wort = strtok(NULL, teiler);
        }
    }

    return count;
}
*/

