//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdio.h>
#include <kernel.h>
#include "kernel_cfg.h"
#include "fatfs.h"

FATFS fatfs;
int last_size;

FRESULT fatfs_open (FIL* fp, const TCHAR* path, BYTE mode)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_open (fp, path, mode);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_close (FIL* fp)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_close (fp);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_read (FIL* fp, void* buff, UINT btr, UINT* br)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_read (fp, buff, btr, br);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_write (FIL* fp, const void* buff, UINT btw, UINT* bw)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_write (fp, buff, btw, bw);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_lseek (FIL* fp, DWORD ofs)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_lseek (fp, ofs);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_sync (FIL* fp)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_sync (fp);
	sig_sem(SEM_FILE);
	return result;
}

int fatfs_tell (FIL* fp)
{
	wai_sem(SEM_FILE);
	int result = f_tell (fp);
	sig_sem(SEM_FILE);
	return result;
}

int fatfs_error (FIL* fp)
{
	wai_sem(SEM_FILE);
	int result = f_error (fp);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_opendir (DIR* dp, const TCHAR* path)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_opendir (dp, path);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_readdir (DIR* dp, FILINFO* fno)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_readdir (dp, fno);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_stat (const TCHAR* path, FILINFO* fno)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_stat (path, fno);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_unlink (const TCHAR* path)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_unlink (path);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_mount (FATFS* fs, const TCHAR* path, BYTE opt)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_mount (fs, path, opt);
	sig_sem(SEM_FILE);
	return result;
}

FRESULT fatfs_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs)
{
	wai_sem(SEM_FILE);
	FRESULT result = f_getfree (path, nclst, fatfs);
	sig_sem(SEM_FILE);
	return result;
}


size_t ffs_read(void *buf, size_t size, size_t sizeofbuf, FILE *fp)
{
	size_t fread = 0;
	fatfs_read((FIL *)fp, buf, size * sizeofbuf, &fread);

	last_size = fread;

	return fread;
}

size_t ffs_write(const void *buf, size_t size, size_t sizeofbuf, FILE *fp)
{
	size_t fwrite = 0;
	fatfs_write((FIL *)fp, buf, size * sizeofbuf, &fwrite);

	last_size += (int)fwrite;

	return fwrite;
}

int ffs_flush(FILE *fp)
{
	fatfs_sync((FIL *)fp);
	return 0;
}

int ffs_error(FILE *fp)
{
	return (int)fatfs_error((FIL *)fp);
}
