#include "filesystem.h"
#include "file.h"

#define __USE_SYSBASE
#include <proto/dos.h>
#include <proto/exec.h>

static BPTR fh;
static BOOL opened;
static ULONG offset;

BOOL openFile(STRPTR device, LONG unit, STRPTR volume, STRPTR name)
{
	LONG bino;

	opened = FALSE;
	fh = 0;

	if (device == NULL) {
		if (fh = Open(name, MODE_OLDFILE))
			return TRUE;
	} else {
		if (openFilesystem(device, unit, volume)) {
			if (readInode(ROOTINO)) {
				bino = lookupName(name, DT_REG);
				if (bino > 0 && readInode(bino)) {
					offset = 0;
					opened = TRUE;
					return TRUE;
				}
			}
			closeFilesystem();
		}
	}

	return FALSE;
}

VOID closeFile(VOID)
{
	if (fh) {
		Close(fh);
		fh = 0;
	}
	if (opened) {
		closeFilesystem();
		opened = FALSE;
	}
}

void _STD_file(void)
{
	closeFile();
}

BOOL seekFile(ULONG off)
{
	if (fh) {
		if (Seek(fh, off, OFFSET_BEGINNING) == -1)
			return FALSE;
	} else
		offset = off;
	return TRUE;
}

LONG readFile(UBYTE *buf, LONG size)
{
	ULONG bytes, total;
	UBYTE *io;

	if (fh)
		return Read(fh, buf, size);
	else {
		total = 0;
		while (size > 0) {
			bytes = readFileBlock(offset, &io);
			if (bytes == 0)
				return (LONG) total;
			if (bytes > size)
				bytes = size;
			CopyMem(io, buf, bytes);
			buf    += bytes;
			offset += bytes;
			size   -= bytes;
			total  += bytes;
		}
		return (LONG)total;
	}
}
