#include <windows.h>
#include <time.h>
#include <stdio.h>
#include <libp.h>

extern int maxfiles;

unsigned char inbuf[512];

FILE output_file = { 0, _F_WRIT | _F_LBUF | _F_TERM,1,0,0,0,0,0,FILTOK };
FILE input_file = { 0, _F_READ | _F_LBUF | _F_TERM,0,0,512,inbuf,inbuf,0,FILTOK };
FILE error_file = { 0, _F_WRIT | _F_LBUF | _F_TERM,1,0,0,0,0,0,FILTOK };

#undef stdin
#undef stdout
#undef stderr

FILE *stdin = &input_file;
FILE *stdout = &output_file;
FILE *stderr = &error_file;

extern int maxfiles;

void _ll_init(void)
{
	DWORD mode ;
	_pstreams[0] = &input_file;
	_pstreams[1] = &output_file;
	_pstreams[2] = &error_file;
	maxfiles = 3;
	stdin->fd = GetStdHandle(STD_INPUT_HANDLE);
	stdout->fd = GetStdHandle(STD_OUTPUT_HANDLE);
	stderr->fd = GetStdHandle(STD_ERROR_HANDLE);

	GetConsoleMode((HANDLE) stdin->fd,&mode) ;
	SetConsoleMode((HANDLE)stdin->fd, mode & ~ENABLE_LINE_INPUT) ;
}
int _ll_open(char *name, int flags)
{
	HANDLE handle = CreateFile(name,flags,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
	if (handle == INVALID_HANDLE_VALUE)
		return 0;
	return handle ;
}
int _ll_creat(char *name, int flags)
{
	HANDLE handle = CreateFile(name,flags,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
	if (handle == INVALID_HANDLE_VALUE)
		return 0;
	return handle ;
}
int _ll_close(int fd)
{
	CloseHandle((HANDLE)fd) ;
	return 1 ;
}
size_t _ll_getpos(int fd)
{
	return SetFilePointer((HANDLE)fd,0,0,FILE_CURRENT) ;
}
int _ll_flags(int flags)
{
	if (flags & _F_WRIT)
		if (flags & _F_READ)
			return GENERIC_READ | GENERIC_WRITE;
		else
			return GENERIC_WRITE;
	else
		return GENERIC_READ;
} 

int _ll_seek(int fd, size_t pos, int origin)
{
	int type ;
	switch(origin) {
		case SEEK_SET:
			type = FILE_BEGIN ;
			break ;
		case SEEK_CUR:
			type = FILE_CURRENT ;
			break ;
		case SEEK_END:
			type = FILE_END;
			break ;
	}
	type = SetFilePointer((HANDLE)fd,pos,0,type);
	if (type == 0xffffffff)
		return 0;
	return 1 ;
}
int _ll_rename(char *old , char *new)
{
	return MoveFile(old,new);
}
int _ll_remove(char *name)
{
	return DeleteFile(name) ;
}
int _ll_write(int fd, void *buf, size_t size)
{
	int written ;
	int rv = WriteFile((HANDLE)fd,buf,size,&written,0);
	if (!rv)
		return rv ;
	if (written != size)
		return 0;
	return rv ;
}
int _ll_read(int fd, void *buf, size_t size)
{
	int read ;
	int rv = ReadFile((HANDLE)fd,buf,size,&read,0) ;
	return read ;
}