/* File handling utility code V1.03 10/2/08
   See futil.h for docs
   Copyright 2008 Jeffrey Lee
   This file is part of WOUM.
   WOUM is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
   WOUM is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   You should have received a copy of the GNU General Public License
   along with WOUM.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef _FUTIL_C
#define _FUTIL_C

#include <stdio.h>

#include "kernel.h"
#include "swis.h"

#include "futil.h"

static _kernel_swi_regs futil_regs;

int futil_readword(FILE *f)
{
	int a,b;
	a = fgetc(f);
	if (a == EOF)
		return EOF;
	b = fgetc(f);
	if (b == EOF)
		return EOF;
	a |= b << 8;
	b = fgetc(f);
	if (b == EOF)
		return EOF;
	a |= b << 16;
	b = fgetc(f);
	if (b == EOF)
		return EOF;
	a |= b << 24;
	return a;
}

int futil_putword(FILE *f,int a)
{
	if (fputc(a & 255,f) == EOF)
		return EOF;
	if (fputc((a>>8) & 255,f) == EOF)
		return EOF;
	if (fputc((a>>16) & 255,f) == EOF)
		return EOF;
	if (fputc((a>>24) & 255,f) == EOF)
		return EOF;
	return 0;
}

int futil_readstring(char *str,int len,FILE *f)
{
	int i,c;
	i = 0;
	while (i < len)
	{
		c = fgetc(f);
		if (c == EOF)
			return EOF;
		str[i++] = c;
		if (c == 0)
			return 0;
	}
	return EOF;
}

void futil_ginfo(char *name,futil_iblock *info)
{
	futil_regs.r[0] = 17;
	futil_regs.r[1] = (int) name;
	if (_kernel_swi(OS_File,&futil_regs,&futil_regs) != 0)
	{
		info->type = 0;
		return;
	}
	info->type = futil_regs.r[0];
	info->load = (unsigned int) futil_regs.r[2];
	info->exec = (unsigned int)futil_regs.r[3];
	info->length = (unsigned int) futil_regs.r[4];
	info->attrib = (unsigned int) futil_regs.r[5];
	if ((info->load & 0xFFF00000) == 0xFFF00000)
	{
		info->filetype = (int) (info->load & 0xFFF00)>>8;
		info->time = ((unsigned long long) (info->exec))+(((unsigned long long) (info->load & 0xFF)) << 32);
	}
	else
	{
		info->filetype = -1;
		info->time = 0;
	}
}

int futil_lfile(char *name,void *ptr)
{
	futil_regs.r[0] = 16;
	futil_regs.r[1] = (int) name;
	futil_regs.r[2] = (int) ptr;
	futil_regs.r[3] = 0;
	if (_kernel_swi(OS_File,&futil_regs,&futil_regs) != 0)
		return 1;
	return 0;
}

int futil_sfile(char *name,void *ptr,int len,int type)
{
	futil_regs.r[0] = 10;
	futil_regs.r[1] = (int) name;
	futil_regs.r[2] = type;
	futil_regs.r[4] = (int) ptr;
	futil_regs.r[5] = ((int) ptr) + len;
	if (_kernel_swi(OS_File,&futil_regs,&futil_regs) != 0)
		return 1;
	return 0;
}

#endif
