/* wmfopen.c (emx+gcc) -- Copyright (c) 1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/winmgr.h>
#include "winmgr2.h"

static int _wmflush (FILE *stream, int c)
{
  int n;
  wm_handle wh;

  if (c == _FLUSH_READ)
    return (0);
  wh = (wm_handle)stream->tmpidx;
  n = stream->ptr - stream->buffer;
  if (n > 0)
    {
      if (c >= 0 && n < stream->buf_size)
        {
          *stream->ptr = (char)c;
          ++n;
          c = -1;               /* Don't write character separately */
        }
      _wm_puts_len (wh, stream->buffer, n);
    }
  stream->ptr = stream->buffer;
  stream->wcount = stream->buf_size;
  if (c >= 0)
    {
      if (stream->buf_size == 0)
        wm_putc (wh, c);
      else
        {
          *stream->ptr++ = (char)c;
          --stream->wcount;
        }
    }
  return (0);
}


FILE *wm_fopen (wm_handle wh)
{
  FILE *stream;

  stream = _newstream ();
  if (stream == NULL)
    return (NULL);
  stream->buffer = NULL;
  stream->ptr = NULL;
  stream->rcount = 0;
  stream->wcount = 0;
  stream->handle = -1;
  stream->flags = _IOOPEN|_IOSPECIAL|_IOBUFNONE|_IOWRT|_IONBF;
  stream->buf_size = 0;
  stream->flush = _wmflush;
  stream->tmpidx = (int)wh;
  return (stream);
}


int wm_fclose (FILE *stream)
{
  int result;

  if ((stream->flags & (_IOOPEN|_IOSPECIAL)) != (_IOOPEN|_IOSPECIAL)
      || stream->flush != _wmflush)
    return (-1);
  result = fflush (stream);
  stream->flags = 0;
  return (result);
}
