/* flushstr.c (emx+gcc) -- Copyright (c) 1990-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <errno.h>

int _flushstream (FILE *stream, int c)
{
  int n, w, fh;
  char ch;

  fh = fileno (stream);
  if (c == _FLUSH_READ)
    {
      /* fill --- not yet used */
    }
  else
    {
      stream->flags |= _IOWRT;        /* Switch to write mode */
      stream->rcount = 0;
      stream->flags &= ~_IOEOF;       /* Clear EOF flag, writing! */
      stream->wcount = 0;             /* Maybe negative at this point */
      if (nbuf (stream))
        _fbuf (stream);
      if (bbuf (stream))
        {
          n = stream->ptr - stream->buffer;
          if (n > 0)            /* n should never be < 0 */
            {
              /* Try to use a single write() call.  This can succeed
                 only if _flush() is called before the buffer is
                 full.  This can happen only when writing a '\n' to a
                 line-buffered file, which is exactly the case where
                 we want to do a single write(). */
              if (n < stream->buf_size)
                {
                  *stream->ptr = (char)c;
                  ++n;
                  c = -1;       /* Don't write character separately */
                }
              w = write (fh, stream->buffer, n);
            }
          else                  /* New or flushed buffer */
            {
              w = 0;
              if (fh >= 0 && fh < _nfiles && (_files[fh] & O_APPEND))
                lseek (fh, 0L, SEEK_END);
            }
          stream->ptr = stream->buffer;
          stream->wcount = stream->buf_size;
          if (c == '\n' && (stream->flags & _IOLBF))
            {
              ch = (char)c;
              if (write (fh, &ch, 1) != 1)
                ++n;            /* n != w */
            }
          else if (c >= 0)      /* -1: already written */
            {
              *stream->ptr++ = (char)c;
              --stream->wcount;
            }
        }
      else
        {
          n = 1;
          ch = (char)c;
          w = write (fh, &ch, 1);
          stream->wcount = 0;
        }
      if (n != w)
        {
          stream->flags |= _IOERR;
          return (EOF);
        }
    }
  return (0);
}
