/* vfopen.c (emx+gcc) -- Copyright (c) 1993-1996 by Eberhard Mattes */

#include <stdio.h>
#include <stdarg.h>
#include <sys/video.h>
#include <emx/io.h>
#include "video2.h"

static int _vflush (FILE *stream, int c)
{
  int n;

  if (c == _FLUSH_FILL)
    return -1;
  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 */
        }
      _v_puts_len (stream->_buffer, n);
    }
  stream->_ptr = stream->_buffer;
  stream->_wcount = stream->_buf_size;
  if (c >= 0)
    {
      if (stream->_buf_size == 0)
        v_putc (c);
      else
        {
          *stream->_ptr++ = (char)c;
          --stream->_wcount;
        }
    }
  return 0;
}


FILE *v_fopen (void)
{
  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 = _vflush;
  stream->_tmpidx = 0;
  if (_setmore (stream, 1) != 0)
    return NULL;
  return stream;
}


int v_fclose (FILE *stream)
{
  int result;

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