/* fgets.c (emx+gcc) -- Copyright (c) 1990-1996 by Eberhard Mattes */

#include <sys/builtin.h>        /* For <sys/fmutex.h> */
#include <sys/fmutex.h>         /* For <sys/rmutex.h> */
#include <sys/rmutex.h>
#include <stdio.h>
#include <stdlib.h>
#include <emx/io.h>

char *fgets (char *buffer, int n, FILE *stream)
{
  int c;
  char *dst;

  if (n <= 0)
    return NULL;
  dst = buffer;

  STREAM_LOCK (stream);
  while (n > 1)
    {
      c = _getc_inline (stream);
      if (c == EOF)
        {
          /* ISO/IEC 9899:1990, 7.9.7.2: "If end-of-file is
             encountered and no characters have been read into the
             array, the contents of the array remain unchanged and a
             null pointer is returned.  If a read error occurs during
             the operation, the array contents are indeterminate and a
             null pointer is returned." */

          if (dst == buffer || ferror (stream))
            {
              STREAM_UNLOCK (stream);
              return NULL;
            }
          else
            break;              /* EOF after reading at least one char */
        }
      *dst++ = (char)c;
      if (c == '\n')
        break;
      --n;
    }
  STREAM_UNLOCK (stream);
  *dst = 0;
  return buffer;
}
