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

/*
	^~len:item:xxxxxxxx
	^~len:item:xxxxxxxx
*/
void add_file(char *afile);
void add_files(char *wild);
void do_item(char *bf, int i, char *fname);
static int totalw,totalu,iswords;
main( int argc, char *argv[])
{
	int i;
	char bf[200];
	time_t t1,t2;

	time(&t1);

	for (;;) {
		fts_init("\\src\\fts", TRUE);
		fts_close();
		printf("Again "); gets(bf);
	} 


	if (argc<2) {
		fts_expire();
		return TRUE;
	}

	for (i=1; i<argc; i++) {
		if (strcmp(argv[i],"expire")==0) fts_expire();
		if (strcmp(argv[i],"words")==0) iswords = TRUE;
		else add_files(argv[i]);
	}
 	if (iswords) return 0;

	fts_close();

	fts_init("\\src\\fts",TRUE);
	time(&t2);
	printf("Speed %d seconds\n",t2-t1);

	printf("Total words %d, total unique %d \n",totalw,totalu);

	for (;;) {
		printf("Enter word to search for? "); gets(bf);
		if (strlen(bf)==0) break;
		fts_searchtest(bf);
	}
	fts_close();
	return 0;

	return 0;
}
void add_files(char *wild)
{
	char tmp[BFSZ];
        struct _finddata_t info;
        long handle,status;

        handle = _findfirst(wild,&info);
        status = handle;
        while (status!= -1) {
                strcpy(tmp,info.name);
		add_file(tmp);
                status = _findnext(handle,&info);
        }
        if (handle!= -1) _findclose(handle);
}
void add_file(char *fname)
{
	char bf[300];
	char *s;
	FILE *f;
	char big[30000];
	int doi;
	int lasti=0;
	big[0] = 0;
		
	f = fopen(fname,"rb");
	for (;!feof(f);) { /*^~length:num:*/
	 	fgets(bf,200,f);
		s = bf;
		if (*s=='^') {
			s = strchr(bf,':');
			if (s!=NULL) doi = atoi(s+1);
			do_item(big,lasti,"rec.humor");
			lasti = doi;
		}
		if (strlen(big)<20000) strcat(big,bf);
	}
	fclose(f);

}
void do_item(char *bf, int i, char *fname)
{
	int nwords,nunique;

	if (i<=0) return;
	fts_add(fname,i,bf);
	fts_stats(&nwords,&nunique);
	printf("Words in item[%d] %d, unique %d\n",i,nwords,nunique);
	totalw += nwords;
	totalu += nunique;
	bf[0] = 0;
}
