#include <stdio.h>
#include "file2.h"
#include "internal.h"

/***************************************************************************
 *
 * Function:    fgets
 *
 * Description:
 *   Read the next nul terminated string from the input file.
 *
 * Input:
 *   string   - Pointer to the output string
 *   count    - maximum length of the output string
 *   stream   - The input file
 *
 * Result:
 *   returns string with text read from file in it.
 *   if count <= 0 return NULL
 *   if count == 1 put null string in string
 *   returns NULL if error or end-of-file found immediately
 */

char *fgets (char *string, size_t count, FILE *stream)
    {
    int  ch;
    char *pointer;
/*
 *  If the count is empty then the result is empty
 */
    if (count <= 0)
        {
	string = NULL;
	}
/*
 *  Read the next character until the end of the string is found.
 */
    else
        {
	pointer = string;
	while (--count)
	    {
	    ch = getc (stream);
/*
 *  If the end of file is found then stop the scan. If this is the first
 *  character in the buffer then return NULL to indicate the end of the
 *  file.
 */
	    if (ch == EOF)
	        {
		if (pointer == string)
		    {
		    pointer = NULL;
		    string  = NULL;
		    break;
		    }
		break;
	        }
/*
 *  Store the input character into the buffer. Stop at the end of the
 *  string.
 */
	    *pointer++ = ch;
	    if (ch == '\n')
	        {
		break;
	        }
	    }
/*
 *  Mark the end of the string.
 */
	if (pointer)
	    {
	    *pointer = '\0';
	    }
        }
/*
 *  Return a pointer to the input string
 */
    return (string);
    }
