/*****************************************************************************

This is file fgetword.c.

*****************************************************************************/

#include "fgetword.h"

int fgetword(                   /* Number of characters in word */
	     FILE *datafile,    /* File holding word */
	     int maxword,       /* Maximum number of letters allowed in word */
	     char word[]        /* Returns the actual word from datafile */
	     )
	
{
  register char c=EOF;
  register char *wd;
  register int n;

           /* First set the character pointer wd to be the address 
	      of the first character in word[]. */
  wd = word;

           /* Now get the next character in the file (note: file 
	      is already open when the function is called), and if 
	      it is not the end of file character, or the maximum 
	      word length has been reached, then... */
  while(wd==word){
    n=maxword;
    while(--n > 0 && (c=getc(datafile))!=EOF){

           /* ...put the character into word and add one to wd (so 
	      that next time we put the next character into word+1), 
	      and check whether that character is whitespace. */
      if(((*wd++ = c) == '\n') || c == ' ' || c == '\r' || c == '\t'){

           /* If it is then get the next character and repeat if the 
	      next character is also white space. */
	while((c=getc(datafile)) == '\n' || c == ' ' || 
	      c == '\r' || c == '\t');

           /* Go back a place in the file so as not to chop off the 
	      first letter of the next word */
	ungetc(c,datafile);
	break;
      }
    }
           /* Go back a place in word so that the last character of 
	      word is not white space unless at EOF */
    wd = wd - 1;
  }
           /* Add `end word' character to word */
  if(wd>=word)
    *wd = '\0';
  else
    *(wd+1) = '\0';

           /* If at end of file return NULL.  Otherwise return the starting 
	      address of word. */

  return(c == EOF && wd == (word-1)) ? 0 : maxword-n;
}
