/* write.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include "rsxnt.h"

int __write (int fd, const void *buf, size_t nbyte)
{
    EMXPROCESS *p = _rsxnt_get_process_ptr();
    DWORD n;

    if (fd >= N_FILES || fd < 0)
	return _rsxnt_errno(EBADF);
    if (p->file[fd].f_handle == INVALID_HANDLE_VALUE)
	return _rsxnt_errno(EBADF);

#ifndef EMX_SYS_LIB
    if (_rsxnt_win32_version == WIN32S
	&& fd < 3 && p->file[fd].f_handle == BAD_FS_HANDLE)
	return win32s_write(fd, buf, nbyte);
#endif

    if (fd == 1 && p->rsxnt_opt.ansi &&
	    GetStdHandle(STD_OUTPUT_HANDLE) == p->file[fd].f_handle)
	if (memchr(buf, '\033', nbyte))
	    return _rsxnt_write_with_ansi(buf, nbyte);

    if (fd == 2 && p->rsxnt_opt.redir &&
	    GetStdHandle(STD_ERROR_HANDLE) == p->file[fd].f_handle)
	fd = 1;

    if (p->file[fd].f_mode == HT_SOCKET)
    {
	if (!_rsxnt_socket_fop.write)
	    return _rsxnt_errno (EBADF);
	else
	    return (*_rsxnt_socket_fop.write)((int) p->file[fd].f_handle, buf, nbyte);
    }

    if (WriteFile (p->file[fd].f_handle, (LPVOID) buf, nbyte, &n, NULL) == FALSE)
	return _rsxnt_get_last_errno();
    else
	return (n);
}
