/*
 *				**** TV NOW MOVIE PROGRAM ****
 *
 * This program extracts the movies from the TV Now
 * data file
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "scantv.h"

char *dayOfWeek(char *s);
int wrong_year(char *flds[], char *title);

main(int argc, char **argv)
{
	char buf[BUFSIZ*2];
	char *flds[TV_ACTOR6], *p;
	int nflds, nents=0, nmovies=0, ntitles;
	FILE *fpin, *fpout, *fp;
	char *title;
	char *chans[10]; /* report all movies on these channels */
	int nchan=0; /* number of channels to watch */

	printf("BUFSIZ=%d\n", BUFSIZ);

	printf("Input file: tvnow.dat\n");
	if ((fpin = fopen("tvnow.dat", "r")) == NULL)
	{
		perror("Can't open tvnow.dat");
		exit(1);
	}

	printf("Output file: tvnow.txt\n");
	if ((fpout = fopen("tvnow.txt", "w")) == NULL)
	{
		perror("Can't open output file tvnow.txt");
		exit(2);
	}

	/*
	 * command line arguments are the files containing wanted movies
	 * make a list of these movies for later
	 */
	argc--; argv++;	/* skip program name */
	wanted_init();		/* open output file (unsorted.txt) for list */

	if (argc < 1)
	{ /* no arguments - use .ini file */
		if ((fp = fopen("scantv.ini", "r")) == NULL)
		{ /* problems */
			fprintf(stderr, "Can't open scantv.ini\n");
			exit(1);
		}
		/* each line contains the name of a file to process */
		while (fgets(buf, sizeof(buf), fp) != NULL)
		{ /* clean up line & pass it to process routine */
			for (p=buf; *p != '\0' && *p != '\n' && *p != '\r'; p++);
			*p = '\0'; /* truncate line */
			if (*buf=='>')
			{ /* add to channel watch */
				chans[nchan++] = strdup(buf+1);
			}
			else
			{
				wanted_process(buf); /* process that file */
			}
		}
		fclose(fp);
	}
	else
	{ /* arguments passed - process them */
		while (argc > 0)
		{
			wanted_process(argv[0]);	/* read & store movies from file */
			argc--; argv++;
		}
	}
	wanted_done(); /* close up file & create sorted list (need.txt) */

	init_movie_titles();		/* initialize list of movies this month */

	/*
	 * list of needed movies created
	 * loop thru schedule & check each movie
	 * Also, make a list of movie names for this month
	 */
	while (read_line(fpin, buf, sizeof(buf))==0)
	{ /* read lines and split into fields */
		if (++nents%100 == 0) printf(".");
		if (nents % 5000 == 0) printf("\n");
		nflds = split_flds(buf, flds, '=', 0, TV_ACTOR6);
		if (nflds < TV_DESC)
		{
			fprintf(stderr, "Line %d too short (%d fields)\n", nents, nflds);
			continue;	/* try next line */
		}
		if (flds[TV_TYPE] == NULL)
		{
			fprintf(stderr, "NULL type found.  nents=%d, nflds=%d\n", nents, nflds);
			continue;
		}
		if (strcmp(flds[TV_TYPE], "MOVIE")) continue;	/* not movie */
		add_movie_title(flds, nflds);	/* add to list of movies */
		if ((title = wanted(flds[TV_TITLE])) == NULL) continue;
		/* title matches - check year if available */
		if (wrong_year(flds, title)) continue; /* different movie */
		/* this is a movie we want - display entry */
		print_movie(flds, title, fpout);
		++nmovies;
		printf("*");
	}

	fclose(fpin);
	fclose(fpout);
	ntitles = close_movie_titles(nchan, chans);

	printf("\n%d entries (%d unique), %d movies found\n",
	       nents, ntitles, nmovies);

	printf("\nPress ENTER to quit: ");
	gets(buf);

	return 0;
}

void
print_movie(char *flds[], char *title, FILE *fp)
{
	char date[9];
	int loc;

	strncpy(date, flds[TV_DATE], 2);
	date[2] = '/';
	strncpy(date+3, flds[TV_DATE]+2, 2);
	date[5] = '\0'; /* don't bother with year */
	/******************************************
	date[5] = '/';
	strncpy(date+6, flds[TV_DATE]+4, 2);
	date[8] = '\0';
	*******************************************/

	if ((loc = find_channel(flds[TV_CHAN])) < 0)
	{
		fprintf(stderr, "Can't find channel (%s)\n", flds[TV_CHAN]);
		return;
	}

	fprintf(fp, "%s %s %s %3s %s (%s) - %s\n",
	        date, flds[TV_TIME], flds[TV_LEN],
	        get_channel_num(loc),
	        title, flds[TV_YEAR], get_channel_name(loc));
	fflush(fp);
}

int wrong_year(char *flds[], char *title)
{ /* check if year specified */
	int yr1, yr2, diff;
	char *p;

	if ((p = strchr(title, '[')) == NULL) return 0; /* no year specified */
	yr1 = atoi(p+1); /* convert to number */
	yr2 = atoi(flds[TV_YEAR]); /* year of movie */
	diff = abs(yr1-yr2);
	if (diff > 1) return 1; /* sometimes year can be slightly different */
	return 0; /* year matches */
}

char *dayOfWeek(char *s)
{
	int m, d, y;
	int dow;
	char *ret;
	static char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

	m = atoi(s);
	d = atoi(s+3);
	y = 2000 + atoi(s+6);
	dow = (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7;
	ret = days[dow];
	return ret;
}

int read_line(FILE *fp, char *buf, int siz)
{
	int c, c2;
	char *p;
	int nchar=0;
	static lastchar=0;	/* used by unread */
	static eol=0;			/* assume MS-DOS */
	int eof=0;

	if (lastchar)
	{ /* second line - one EOL character */
		buf[0] = lastchar;	/* char from prev read */
		p = buf+1;
		lastchar = 0;	/* clear flag */
	}
	else p = buf;		/* where to start reading */
	
	while ((c = fgetc(fp)) != EOF)
	{ /* read characters until end of line */
		nchar++;
		if (nchar >= siz)
		{
			fprintf(stderr, "Buffer overflow (%d chars)\n", nchar);
			return -2;
		}
		if (c=='\r' || c=='\n')
		{ /* end of line */
			*p='\0';	/* truncate line */
			if (eol==0)
			{ /* first line read - determine if Unix or MS-DOS */
				c2 = fgetc(fp);	/* get second EOL char */
				if (c==c2)
				{ /* same char - file starts w/ two empty lines */
					eol = 1;	/* 1 EOL character */
					lastchar = c2;	/* save for next line read */
				}
				else if (c2!='\r' && c2!='\n')
				{ /* one  EOL characters */
					eol = 1;
					lastchar = c2;	/* save for next line */
				}
				else
				{ /* two EOL characters */
					eol = 2;
				}
			}
			else
			{ /* end of line - read extra EOL character if needed */
				if (eol==2) c = fgetc(fp);
			}
			return 0;	/* end of line - return */
		}
		else
		{ /* regular character - add to line */
			*p++ = c;
		}
	}
	*p = '\0';	/* truncate line */
	return (c==EOF);	/* could be EOF */
}


