#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <ctype.h>
#include "db.h"

int load(char *szFilename) {
    char            *prgText;
    struct stat     stStat;
    FILE            *pFile;
    size_t          nSize;
    int             i;
    char            *pLeft;

	DB_Create();
    pFile = fopen(szFilename,"r");
    if (NULL==pFile)
        return 0;

    if (stat(szFilename,&stStat)) {
        printf("stat failure\n");
        return 0;
    }

    nSize = stStat.st_size;
    prgText= (char*)malloc(nSize);

    i = fread(prgText,1,nSize,pFile);
    if (i&&ferror(pFile)) {
        free(prgText);
        return 0;
    }

    pLeft = prgText;
    for (i=0;i<nSize;i++) {
        switch (prgText[i]) {
            case  ' ':
            case  ',':
            case  ':':
            case  '.':
            case '\n':
            case '\r':
            case  ';':
            case  '?':
            case '\'':
            case  '!':
            case  '(':
            case  ')':
            case  '"':
            case '\v':
            case '\t':
                prgText[i]='\0';
                if (*pLeft != '\0')
                    DB_Add(pLeft);
                pLeft = prgText+i+1;
                break;
#ifdef NOCASE
            default:
                prgText[i]=tolower(prgText[i]);
#endif
        }
    }

    DB_DisplayResult();
    DB_Destroy();
    free(prgText);

    return 1;
}

int main(int argc,char **argv) {
    if (argc < 2) {
        fprintf(stderr,"tell me the file\n");
        return 1;
    }
    load(argv[1]);
    return 0;
}
