#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "eliza.h"

//random between a and b
int randomize(int a, int b)
{
    return rand() % (b-a) + a;
}

//get len of a word in a line, spc or null terminated
int getLen(const char * line)
{
    int len = 1;
    while(*(line+len)!=0 && *(line+len)!=' ')
        len++;
    return len;
}

//transform to upper case string
void strToUpper(char * line)
{
    int i=0;
    while(*(line+i)!=0)
    {
        *(line+i) = toupper(*(line+i));
        i++;
    }
}

//replace word if needed
const char * conjugate(char * word)
{
    int i;
    for (i=0;i<7;i++)
        if (strncmp(conjugation[i][0], word, strlen(conjugation[i][0]))==0)
            return conjugation[i][1];
    return word;
}

//find key
int getKey(const char * question)
{
    for (int i=0;i<36;i++)
        if (strncmp(question,keyword[i], strlen(keyword[i])) == 0)
            return i;
    return 35;
}

//process eliza
void eliza(char * question, char * answer)
{
    strToUpper(question);
    int a;
    if((a = getKey(question))!=35)
    {
        //got a keyword, choose one reply
        int choice = randomize(keyReply[a][0],keyReply[a][1]);
        strcpy(answer, reply[choice]);
        //if reply is * terminated
        char * star = strchr(answer,'*');
        if (star)
        {
            *star = 0;
            //copy all remainder of the line , replace some word if needed
            char * start = &question[strlen(keyword[a])-1];
            while(start)
            {
                const char * word = conjugate(start);
                strncat(answer, word, getLen(word));
                start = strchr(start+1,' ');
            }
        }
    }
    else
        strcpy(answer, "CONTINUE");
}

int main()
{

    char question[100],
         answer[1000] = {0};
    srand ( time(NULL) );

    while(strcmp(question,"EXIT") && strcmp(question,"exit"))
    {
        gets(question);

        eliza(question, answer);

        printf("%s\n",answer);
    }
    
    return 0;
}
