#include "msys.h"
#include "Shlwapi.h"
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include "../resources/resource.h"

unsigned int memopen(char *name)
{
	MEMFILE *memfile;

	memfile = (MEMFILE *)msys_mallocAlloc(sizeof(MEMFILE));

	HRSRC		rec;
	HGLOBAL		handle;

	rec = FindResource(NULL, MAKEINTRESOURCE(IDR_XMAUDIO1), "XMAUDIO");
	handle = LoadResource(NULL, rec);

	memfile->data = LockResource(handle);
	memfile->length = SizeofResource(NULL, rec);
	memfile->pos = 0;

	return (unsigned int)memfile;
}

unsigned int memopen2(int resCode)
{
	MEMFILE *memfile;

	memfile = (MEMFILE *)msys_mallocAlloc(sizeof(MEMFILE));

	HRSRC		rec;
	HGLOBAL		handle;

	rec = FindResource(NULL, MAKEINTRESOURCE(resCode), "XMAUDIO");
	handle = LoadResource(NULL, rec);

	memfile->data = LockResource(handle);
	memfile->length = SizeofResource(NULL, rec);
	memfile->pos = 0;

	return (unsigned int)memfile;
}


void memclose(unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	msys_mallocFree(memfile);
}

void msys_memcpy( void *dst, const void *ori, int amount )
{
	_asm mov edi, dst
		_asm mov esi, ori
		_asm mov ecx, amount
		_asm rep movsb
}

int memread(void *buffer, int size, unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	if (memfile->pos + size >= memfile->length)
		size = memfile->length - memfile->pos;

	msys_memcpy(buffer, (char *)memfile->data+memfile->pos, size);
	memfile->pos += size;

	return size;
}

void memseek(unsigned int handle, int pos, signed char mode)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	if (mode == SEEK_SET) 
		memfile->pos = pos;
	else if (mode == SEEK_CUR) 
		memfile->pos += pos;
	else if (mode == SEEK_END)
		memfile->pos = memfile->length + pos;

	if (memfile->pos > memfile->length)
		memfile->pos = memfile->length;
}

int memtell(unsigned int handle)
{
	MEMFILE *memfile = (MEMFILE *)handle;

	return memfile->pos;
}
