/*
 *				**** WANTED ****
 *
 * This file contains routines used to determine if
 * a given movie is on the wanted list
 */

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

#include "scantv.h"

static FILE *fp, *pp;

void
wanted_init(void)
{
	if ((pp = fopen("unsorted.txt", "wt")) == NULL)
	{
		perror("Can't open pipe");
		exit(4);
	}
}

void
wanted_process(char *fname)
{
	FILE *fp;
	char buf[BUFSIZ], buf2[BUFSIZ];

	if ((fp = fopen(fname, "r")) == NULL)
	{
		fprintf(stderr, "Can't open %s\n", fname);
		perror("Can't open wanted file");
		return;
	}

	while (fgets(buf, sizeof(buf), fp))
	{
		process_title(buf2, buf);
		if (buf2[0] == '\0') continue;	/* ignore blank lines */
		fprintf(pp, "%s|%s", buf2, buf);
	}
}

void
wanted_done(void)
{
	fclose(pp);
   system("sort unsorted.txt > need.txt");
	if ((fp = fopen("need.txt", "r")) == NULL)
	{
		perror("Can't open need.txt");
		exit(5);
	}
}

char *
wanted(char *str)
{
	static char tbuf[BUFSIZ], title[BUFSIZ];
	static first_time = 1;
	char *p, *q;

   if (first_time)
   {
   	*tbuf = '\0';
      first_time = 0;
   }

   process_title(title, str);

   /* if past where we want to be, rewind */
   if (strcmp(str, tbuf) < 0)
   {
   	rewind(fp);
      *tbuf = '\0';
   }

	while (strcmp(title, tbuf) > 0)
   { /* not found yet, keep looking */
   	if (fgets(tbuf, sizeof(tbuf), fp) == NULL)
      { /* EOF */
      	rewind(fp);
      	break;
      }
      for (p=tbuf; *p != '\0' && *p != '|' && *p != '\r'
			&& *p != '\n'; p++);
      if (*p != '\0') *p++ = '\0';
   }

   if (strcmp(title, tbuf) == 0)
   {
	   for (q=p; *q != '\0' && *q != '\n' && *q != '\r'; q++);
	   *q = '\0';
	   return p;
   }
   else return NULL;
}

void
process_title(char *dest, char *src)
{ /* compress, make all lower case, drop non-alphanumeric */
	if (strncmp(src, "The ", 4)==0) src+= 4;
	if (strncmp(src, "An ", 3)==0) src += 3;
	if (strncmp(src, "A ", 2)==0) src += 2;

	while (*src != '\0' && *src != '|')
	{
		if (isalnum(*src))
		{ /* alpha-numeric - keep */
			*dest = tolower(*src);
			dest++;
		}
		src++;
	}
	*dest = '\0';
}

