#include "tn_2sf.h"
#include "TN_2SF.bin_rev.h"
#include "vio2sf/vio2sf.h"
#include <stdlib.h>

const char verstag[] = VERSTAG;

struct ExecIFace *IExec;
struct Interface *INewlib;
struct DOSIFace *IDOS;

static int32 xsf_open (struct TNDecHandle *handle, void *buf, uint32 len);
static void xsf_close (struct TNDecHandle *handle);
static int32 xsf_process (struct TNDecHandle *handle, void *buf, uint32 len);

xsfiface_t ixsf = {
	xsf_open,
	xsf_close,
	xsf_process,
};

xsfiface_t *_start (char *argstr, int32 arglen, struct ExecBase *SysBase) {
	IExec = (struct ExecIFace *)SysBase->MainInterface;
	return &ixsf;
}

static int32 xsf_open (struct TNDecHandle *handle, void *buf, uint32 len) {
	INewlib = handle->newlib;
	IDOS = handle->dos;
	return xsf_start(buf, len) != XSF_FALSE;
}

static void xsf_close (struct TNDecHandle *handle) {
	xsf_term();
	IDOS = NULL;
	INewlib = NULL;
}

static int32 xsf_process (struct TNDecHandle *handle, void *buf, uint32 len) {
	return xsf_gen(buf, len) >> 2;
}

int xsf_get_lib(char *pfilename, void **ppbuffer, unsigned *plength) {
	BPTR file;
	file = IDOS->Open(pfilename, MODE_OLDFILE);
	if (file) {
		int64 file_size;
		void *buffer;
		file_size = IDOS->GetFileSize(file);
		if (file_size != -1) {
			buffer = malloc(file_size);
			if (buffer) {
				IDOS->Read(file, buffer, file_size);
				*ppbuffer = buffer;
				*plength = file_size;
				IDOS->Close(file);
				return 1;
			}
		}
		IDOS->Close(file);
	}
	return 0;
}
