/*
    Copyright (C) 1995-1997
        Rainer Schnitker, Heeper Str. 283, 33607 Bielefeld
        email: rainer@mathematik.uni-bielefeld.de

    All rights reserved
*/

#include <rsxnt.h>

/* local stuff for win32s */
#define BUFSIZE 5192
static int win32s;                  /* win32s environment       */
static int win32s_heap;             /* win32s io for rsxide     */
static char *iobuf;
static int iRead, iWrite;

BOOL WINAPI win32s_init(void)
{
    if (!win32s)
        return FALSE;
    iRead = iWrite = 0;
    iobuf = HeapAlloc(GetProcessHeap(), 0, BUFSIZE);
    if (iobuf) {
        win32s_heap = 1;
        return TRUE;
    } else {
        win32s_heap = 0;
        return FALSE;
    }
}

int WINAPI win32s_read(int fd, char *buf, size_t nbyte)
{
    int i;

    if (!win32s_heap || iRead >= iWrite)
        return -1;

    for (i = 0; i < nbyte; ++i) {
        buf[i] = iobuf[iRead++];
        if (buf[i] == '\n')
            break;
        if (iRead > iWrite)
            break;
    }
    if (iRead > iWrite)
        iRead = iWrite = 0;

    return i;
}

int WINAPI win32s_write(int fd, const void *buf, size_t nbyte)
{
    if (!win32s_heap)
        return -1;

    if (nbyte > BUFSIZE)
        nbyte = BUFSIZE;
    if (nbyte + iWrite > BUFSIZE)
        nbyte = BUFSIZE - iWrite;

    memcpy(iobuf + iWrite, buf, nbyte);
    iWrite += nbyte;

    return nbyte;
}
