#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FALSE 0
#define TRUE (!FALSE)
/* My file routines that replace fopen, fclose, fread, fwrite, fseek */
typedef struct {int h; int eof; } MYFILE;
static MYFILE hand[10];
static int nhand;
FILE *s_fopen(const char *fname,const char *mode)
{
	int i;
	int m=0;
	int h;
	int *p=NULL;

	emsg("FTS Open %s, mode %s \n",fname,mode);

	if (strcmp(mode,"rb")==0) m =  _O_RDONLY  | _O_BINARY;
	else if (strcmp(mode,"wb")==0) m = _O_CREAT | _O_TRUNC | _O_BINARY;
	else if (strcmp(mode,"a+b")==0) m = _O_CREAT | _O_APPEND | _O_BINARY | _O_RDWR;
	else if (strcmp(mode,"r+b")==0) m = _O_RDWR | _O_BINARY;
	else if (strcmp(mode,"w+b")==0) m = _O_RDWR | _O_CREAT | _O_TRUNC | _O_BINARY;
	else {
	 	emsg("Fatal error, could not open file with correct mode {%s} \n",mode);
		*p = 0;
	}	
 	h = open(fname,m,_S_IREAD | _S_IWRITE);
	if (h<0) return NULL;
	for (i=0; i<nhand; i++) {
	 	if (hand[i].h<0) break;
	}
	if (i==nhand) nhand++;
	emsg("Open using handle %d %d \n",i,h);
	hand[i].h = h;
	hand[i].eof = FALSE;
	return (FILE *) &hand[i];
}
void s_fclose(FILE *f)
{
	MYFILE *v = (MYFILE *) f;
	emsg("Close handle %d \n",v->h);
	close(v->h);
	v->h = -1;
	v->eof = FALSE;
}
size_t s_fread(void *bf, size_t size, size_t count, FILE *f)
{
	MYFILE *v = (MYFILE *) f;
	size_t r;
	r = read(v->h,bf,size*count);
	if (r < size*count) v->eof = TRUE;
	return r;
}
size_t s_fwrite(void *bf, size_t size, size_t count, FILE *f)
{
	MYFILE *v = (MYFILE *) f;
	return write(v->h,bf,size*count);
}
int s_fseek(FILE *f, long offset, int origin)
{	 
	MYFILE *v = (MYFILE *) f;
	int r;
	r =  lseek(v->h,offset,origin);
	if (r>=0) return 0;
	return -1;
}
int s_feof(FILE *f)
{
	MYFILE *v = (MYFILE *) f;
 	return v->eof;
}
long s_ftell(FILE *f)
{
	MYFILE *v = (MYFILE *) f;
 	return tell(v->h);
}
