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

#include "rsxnt.h"

void _rsxnt_init_files(EMXPROCESS *p)
{
    static int inited = 0;

    int i;
    HANDLE hFile;
    BOOL console = FALSE;
    int fd;

    if (inited)
	return;
    else
	inited = 1;

    /* for Win32s get 40 Files */
    if (_rsxnt_win32_version == WIN32S) {
	SetHandleCount(N_FILES);
	p->rsxnt_opt.ansi = 0;
    }

    InitializeCriticalSection(&(p->CritSectFiles));

    for (i = 0; i < N_FILES; i++)
	p->file[i].f_handle = INVALID_HANDLE_VALUE;

    /* set stdhandles to 0-2 */
    hFile = GetStdHandle(STD_INPUT_HANDLE);
    if (hFile != INVALID_HANDLE_VALUE) {
	p->file[0].f_mode = HT_DEV_CON;
	p->file[0].f_flags = 0;
	p->file[0].f_handle = hFile;
	console = TRUE;
	// FlushConsoleInputBuffer(hFile);
    }
    hFile = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hFile != INVALID_HANDLE_VALUE) {
	p->file[1].f_mode = HT_DEV_CON;
	p->file[1].f_flags = 0;
	p->file[1].f_handle = hFile;
	console = TRUE;
    }
    hFile = GetStdHandle(STD_ERROR_HANDLE);
    if (hFile != INVALID_HANDLE_VALUE) {
	p->file[2].f_mode = HT_DEV_CON;
	p->file[2].f_flags = 0;
	p->file[2].f_handle = hFile;
	console = TRUE;
    }

    p->umask_bits = 0022;
    p->bConsoleApp = console;

    if (p->bConsoleApp == FALSE) {  /* dummy files for (0-2) */
	p->file[0].f_handle = BAD_FS_HANDLE;
	p->file[1].f_handle = BAD_FS_HANDLE;
	p->file[2].f_handle = BAD_FS_HANDLE;
    }
    fd = 3;

    /* scan the first 40 Win32 files */
    for (i = 0; i < N_FILES; i++) {

	DWORD type = _rsxnt_get_ht_type((HANDLE)i);

	if ((HANDLE)i == p->file[0].f_handle ||
	    (HANDLE)i == p->file[1].f_handle ||
	    (HANDLE)i == p->file[2].f_handle)
	    type = 0xffffffff;

	if (type != 0xffffffff) {
	    p->file[fd].f_mode = type;
	    p->file[fd].f_flags = 0;
	    p->file[fd].f_handle = (HANDLE) i;
	    _rsxnt_check_console_handle(p, fd);
	    fd++;
	}
    }
}
