/* wmfopen.c (emx+gcc) -- Copyright (c) 1993-2000 by Eberhard Mattes */

#include <stdio.h>
#include <stdarg.h>
#include <sys/winmgr.h>
#include <emx/io.h>
#include "winmgr2.h"

static int _wmflush (FILE *stream, int c)
{
  int n;
  wm_handle wh;

  if (c == _FLUSH_FILL)
    return -1;
  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_putsn (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;
  if (_setmore (stream, 1) != 0)
    return NULL;
  return stream;
}


int wm_fclose (FILE *stream)
{
  int result;

  if ((stream->_flags & (_IOOPEN|_IOSPECIAL)) != (_IOOPEN|_IOSPECIAL)
      || stream->_flush != _wmflush)
    return -1;
  result = fflush (stream);
  _closestream (stream);
  return result;
}
