/* $Id: gobble.c,v 1.5 1998/10/17 13:24:50 fraserm Exp $
   $Log: gobble.c,v $
   Revision 1.5  1998/10/17 13:24:50  fraserm
   ANSI-fied the code
   added "-" option to allow futrther options from standard input

   Revision 1.4  1998/03/08 22:44:13  fraserm
   screen refresh by interval timer for xagm
   doesn't sort dictionary unless it has to

   Revision 1.3  1996/09/13 20:35:06  fraser
   can now read from standard input
   no longer uses stat() and huge fread() (and is barely slower)

 * Revision 1.2  1996/09/12  14:20:56  fraser
 * add module version printing
 *
 * Revision 1.1  1996/09/12  13:18:39  fraser
 * Initial revision
 *
*/
/* gobble.c: dictionary file reading function for agm
*/

char gobble_RCSid[] = "$Revision: 1.5 $";

#include "agm.h"

void gobble_file (char *filename, char *command)
{
  FILE *fp;
  int is_a_tty2 = 0;
  unsigned int i;
  unsigned int before_count = wordcount;
  char *array, inword[WORDLEN], ch;

  if (notquiet) {
    printf ("%s: reading %s into dictionary:", command,
            (strcmp (filename, STANDARDIN) == 0)
             ? "standard input" : filename);
    fflush (stdout);
  }
  if (strcmp (filename, STANDARDIN) != 0) { /* not reading the standard input,
                                               so we must open the file */
    if ((fp = fopen (filename, "r")) == NULL) {
      fprintf (stderr, "%s: cannot open %s\n",
	       command, filename);
      exit (-1);
    }
  }
  else { /* we *are* reading from stdin, so we might have to ask user */
    if ((is_a_tty2 = isatty (0))) { /* standard input is a terminal */
      printf ("%s: (EOF on new line when done)\n", command);
      fflush (stdout);
    }
    fp = stdin;
  }
  while (!feof (fp)) {
    while (!feof (fp)
	   && strchr (SEPCHARS, (ch = fgetc(fp))) != NULL); /* skip crap */
    inword[0] = LOWER(ch);
    i = 1;
    while (!feof (fp)
	   && strchr (SEPCHARS, (ch = fgetc(fp))) == NULL) { /* read a word */
      inword[i++] = LOWER(ch);
    }
    if (!feof (fp)) {
      inword[i++] = '\0';
      if ((array = (char *) malloc (i)) == NULL) {
	fprintf (stderr, "%s: unable to allocate %d bytes for an input word\n",
		 command, i);
	exit (-1);
      }
      strcpy (array, inword);
      if (addword (array, &lstart, &lend) != 0) {
	fprintf (stderr,
		 "%s: error adding word; char number %d, word number %d\n",
		 command, i, wordcount);
	exit (-1);
      }
      ++wordcount;
    }
  }
  if (notquiet) printf (" %d words\n", wordcount - before_count);
}

