/* MailExtract.c 
**
** Brian Gragg  4/30/96
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/types.h>
#include <dos/dos.h>
#include <proto/dos.h>
#include <stat.h>

#define MAXHEADERLENGTH 51

char version[]="$VER: MailExtract V1.5";
char search[20][80], file[20][100], Count[20], line[MAXHEADERLENGTH][1000];

void main(int argc, char **argv)
{
	char *outfile, keepfile[] = "t:mailextract.keep", safefile[100];
	FILE *inputfp, *controlfp, *outputfp = NULL;
	int i,j, sets, cnt;
	BOOL foundFrom = FALSE;
	BOOL foundTo   = FALSE;
	struct stat st;
	
	/* check for valid input file */
	if (-1 == stat(argv[1],&st)) {
		printf("%s: Input file not found - %s\n",argv[0],argv[1]);
		exit(10);
	}
	
	/* check if file is empty */
	if (st.st_size == 0) {
		/* no mail received */
		puts("No mail recieved. \n");
		exit(0);
	}
	
	remove(keepfile);  /* clear any old keepfile since we will start a new one */
	
	if (argc != 3){
		printf("Usage:  %s infile controlfile\n",argv[0]);
		exit(10);
	}
	
	/* check that the keepfile can be opened */
	if (NULL == (outputfp = fopen(keepfile,"w"))){
		printf("%s: Error opening temp file - %s\n",argv[0],keepfile);
		exit(10);
	}
	fclose(outputfp);
	outputfp = NULL;

	/* check for control file */
	if (NULL == (controlfp = fopen(argv[2],"r"))){
		printf("%s: Control file not found - %s\n",argv[0],argv[2]);
		exit(10);
	}
	
	sets=0;
	
	/* read the control file */
	while (!feof(controlfp)) {
		/* FIRST - get a pattern */
		do {
			if (NULL == (fgets(search[sets],80,controlfp))) {
				printf("%s: Error reading control file %s\n",argv[0],argv[2]);
				fclose(controlfp);
				exit(10);
			}
			/* strip trailing carriage returns */
			if (search[sets][strlen(search[sets])-1] == '\n')
				search[sets][strlen(search[sets])-1] = '\0';
		} while (search[sets][0] == ';' && !feof(controlfp));
		/* SECOND - get a filename */
		do {
			if (NULL == (fgets(file[sets],100,controlfp))) {
				printf("%s: Error reading control file %s\n",argv[0],argv[2]);
				fclose(controlfp);
				exit(10);
			}
			if (file[sets][strlen(file[sets])-1] == '\n')
				file[sets][strlen(file[sets])-1] = '\0';
		} while (file[sets][0] == ';' && !feof(controlfp));
		Count[sets++] = 0;
	}
	fclose(controlfp);
	
	/* pattern match will be case insensative so convert to upper case */
	for (i=0; i<sets; i++)
		strupr(search[i]);
		
	Count[sets] = 0;
	/* okay, open the mail file for real this time */
	if (NULL == (inputfp = fopen(argv[1],"r"))){
		printf("%s: Input file not found - %s\n",argv[0],argv[1]);
		exit(10);
	}

	cnt = 0;
	
	/* start searching for headers */
	while (!feof(inputfp) && (NULL != fgets(line[cnt],999,inputfp))) {
		/* From and To lines found and now a \n, so we just found the end of the header */
		if (foundFrom && foundTo && line[cnt][0]=='\n') {
			/* New Message Found */
			outfile = NULL;
			/* look for a match from the search pattern */
			for (i=0; i<cnt && outfile==NULL; i++) 
				for (j=0; j<sets && outfile==NULL; j++) {
					strcpy(line[MAXHEADERLENGTH-1],line[i]);
					if (astcsma(strupr(line[MAXHEADERLENGTH-1]),search[j]) > 0) {
						outfile = file[j];
						Count[j]++;
					}
				}
			if (outfile == NULL) {
				outfile = keepfile;
				Count[sets]++;
			}
			/* close the old save file and open the new */
			if (NULL != outputfp) fclose(outputfp);
			if (NULL == (outputfp = fopen(outfile,"a"))) {
				/* open failed, save the stuff safely and exit */
				strcpy(safefile,argv[1]);
				strcat(safefile,"-SAVED");
				printf("%s: Error opening output file %s\n",argv[0],outfile);
				printf("%s: Attempting to save rest of input file to %s\n",argv[0],safefile);
				if (NULL == (outputfp = fopen(safefile,"a")))
					printf("%s:   Unable to save rest of input file, input file unchanged\n",argv[0]);
				for (i=0; i<=cnt; i++)
					fputs(line[i],outputfp);
				while (!feof(inputfp)) {
					if (NULL != fgets(line[0],1000,inputfp))
						fputs(line[0],outputfp);
				}
				fclose(inputfp);
				printf("%s: Input file %s is unchanged\n",argv[0],argv[1]);
				printf("%s: New file %s holds copy of unprocessed messages\n",argv[0],safefile);
				exit(10);
			}
			/* save the header we read to the output file */
			for(i=0; i<=cnt; i++)
				fputs(line[i],outputfp);
			foundFrom = foundTo = FALSE;
			cnt = 0;
		}
		/* Look for a FROM line */
		else if (0 == strnicmp(line[cnt],"From ",5)) {
			if (foundFrom) {
				for(i=0; i<=cnt-1; i++)
					fputs(line[i],outputfp);/* clear list */
				strcpy(line[0],line[cnt]); /* copy new line to start of list */
				cnt = 0;                   /* reset list */
			}
			cnt++;
			foundFrom = TRUE;
		}
		/* Look for a TO: line */
		else if (foundFrom && (0 == strnicmp(line[cnt],"To: ",4))) {
			cnt++;
			foundTo = TRUE;
		}
		/* we may be in a header, so don't save the data, just buffer it      */
		/* until we find out.  If we are not in a header, we'll save the data */
		/* to the current file. If we are in a header, we'll save it to the   */
		/* appropriate file once the whole header has been read.              */
		else if (foundFrom) {
			if (line[cnt][0]=='\n') {
				/* False From Line, save the stored up stuff to the old outfile */
				for(i=0; i<=cnt; i++)
					fputs(line[i],outputfp);
				cnt = 0;
				foundFrom = FALSE;
			}
			else
				cnt++;
		}
		/* We're not in a header, so just save the line to the correct file */
		else
			fputs(line[cnt],outputfp);

		/* If we haven't found the end of header yet, we are probably not in a header */
		if (cnt > MAXHEADERLENGTH-2) {  
			for(i=0; i<=cnt; i++)
				fputs(line[i],outputfp);
			cnt = 0;
			foundFrom = FALSE;
		}
	}

	/* If we were buffering up lines cause we thought we might be in a header, */
	/* but weren't, then we need to save off the lines we've buffered.         */
	if (cnt>0)
		for (i=0; i<cnt; i++)
			fputs(line[i],outputfp);
	
	/* Close up the files */
	fclose(inputfp);
	if (outputfp != NULL)
		fclose(outputfp);
	
	/* Print what's been saved */
	for (i=0; i<sets; i++) 
		if (Count[i] > 0) 
			printf("%s: %d messages. \n",FilePart((STRPTR) file[i]),Count[i]);
	
	if ( Count[sets] > 0)
		printf("%s: %d messages. \n",FilePart((STRPTR) argv[1]),Count[sets]);

	/* save the old input file with a .bak extension */
	strcpy(safefile,argv[1]);
	strcat(safefile,".bak");
	remove(safefile);
 	sprintf(file[0],"copy %s %s",argv[1],safefile);
	system(file[0]);
	/* save the keepfile stuff to the original input file name */
	remove(argv[1]);
	sprintf(file[0],"copy %s %s",keepfile,argv[1]);
	system(file[0]);
	remove(keepfile);
	
}


