#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#ifdef __MWERKS__
#include "Mac.h"
#endif
#ifdef WIN32
#include <windows.h>
#include <io.h>
#endif
#include <ctype.h>
#include <string.h>
#include <assert.h>

#ifdef VMS
#include <unixio.h>
#endif
#ifndef WIN32
#ifndef Mac
#ifndef NOUNISTD
#include <unistd.h>
#endif
#endif
#endif        
#ifdef OS2
#include <io.h>
#endif
#ifndef NO_FCNTL
#include <fcntl.h>
#else
/*RHP not for mac*/
#ifndef Mac
#include <file.h>
#endif
#endif


#include "emsg.h"
#include "str.h"
#include "sary.h"
#include "lib.h"
char *get_ahead(String *sitem, char *head);
#include "group.h"
#include "hist.h"
#include "item.h"
#include "chan.h"
#include "db.h"
#include "dbf.h"

#include "myraw.h"

#undef read
#undef write
#undef open
#undef close
#undef lseek


static FILE *hand[200];
int mac_handle(void)
{
	int i;
	for (i=0; i<100; i++) {
		if (hand[i]==NULL) return i;
	}
	return -1;
}
int mac_length(int h)
{
	int e,x;
	if ((h<0) || (h>100)) {imsg("Cannot close handle %d\n",h); return -1;}
	if (hand[h]==NULL) {imsg("Cannot close handle %d, not open\n",h); return -1;}	
	x = ftell(hand[h]);
	fseek(hand[h],0,SEEK_END);
	e = ftell(hand[h]);
	fseek(hand[h],x,SEEK_SET);
	return e;
}
int mac_open( const char *filename, int oflag, int xx )
{
	int h;
	char mode[BFSZ];

	if (oflag&O_APPEND) strcpy(mode,"ab");
	else if (oflag&O_RDONLY) strcpy(mode,"rb");
	else if (oflag&O_WRONLY) strcpy(mode,"wb");
	else if (oflag&O_RDWR) strcpy(mode,"ab+");
	else strcpy(mode,"rb");

	h = mac_handle();
	if (h<0) return h;
	imsg("mac_open(%s,%s,h=%d)\n",filename,mode,h);
	hand[h] = fopen(filename,mode);
	if (hand[h]==NULL) {
		errno = ENOENT;
		return -1;
	}
	return h;
}
int mac_fileno(int h)
{
	return fileno(hand[h]);
}
int mac_close(int h)
{
	imsg("mac_close(%d)\n",h);
	if ((h<0) || (h>100)) {imsg("Cannot close handle %d\n",h); return -1;}
	if (hand[h]==NULL) {imsg("Cannot close handle %d, not open\n",h); return -1;}
	fclose(hand[h]);
	hand[h] = NULL;
	return 0;
}
int mac_read( int h, void *buffer, unsigned int count )
{
	if ((h<0) || (h>100)) return -1;
	if (hand[h]==NULL) return -1;
	return fread(buffer,1,count,hand[h]);
}
int mac_write( int h, const void *buffer, unsigned int count )
{
	if ((h<0) || (h>100)) return -1;
	if (hand[h]==NULL) return -1;
	return fwrite(buffer,1,count,hand[h]);
}
long mac_lseek( int h, long offset, int origin )
{
	if ((h<0) || (h>100)) return -1;
	if (hand[h]==NULL) return -1;
	return fseek(hand[h],offset,origin);			
}