/***
	psx 360 :D
***/
#include <xtl.h>
#include <stdio.h>
#include <stdlib.h>

#include "PsxCommon.h"
#include "DEBUG.h"

int SysInit();
void SysReset();
void SysClose();
void SysPrintf(char *fmt, ...);
void *SysLoadLibrary(char *lib);
void *SysLoadSym(void *lib, char *sym);
const char *SysLibError();
void SysCloseLibrary(void *lib);
void SysUpdate();
void SysRunGui();
void SysMessage(char *fmt, ...);

// Plugin structure
#include "GamecubePlugins.h"
/*
PluginTable plugins[] =
	{ PLUGIN_SLOT_0,
	  PLUGIN_SLOT_1,
	  PLUGIN_SLOT_2,
	  PLUGIN_SLOT_3,
	  PLUGIN_SLOT_4,
	  PLUGIN_SLOT_5,
	  PLUGIN_SLOT_6,
	  PLUGIN_SLOT_7 
};
*/
PluginTable plugins[] =
	{ PLUGIN_SLOT_0,
	  PLUGIN_SLOT_1,
	  PLUGIN_SLOT_2,
	  CDR_ISO_PLUGIN,//PLUGIN_SLOT_3,
	  SPU_PEOPS_PLUGIN,//SPU_NULL_PLUGIN
	  PLUGIN_SLOT_5,
	  PLUGIN_SLOT_6,
	  PLUGIN_SLOT_7 
};

int stop = 0;
long LoadCdBios;

const char *SysLibError() {
	return NULL;
}

void SysPrintf(char *fmt, ...) {
	va_list list;
	char msg[512];

	va_start(list, fmt);
	vsprintf(msg, fmt, list);
	va_end(list);

	//fprintf(emuLog, "%s", msg);
	OutputDebugStringA(msg);
}

int SysInit() {
    SysPrintf("start SysInit()\r\n");
    SysPrintf("psxInit()\r\n");
	psxInit();

    SysPrintf("LoadPlugins()\r\n");
	if(LoadPlugins()==-1)
		SysPrintf("ErrorLoadingPlugins()\r\n");
    SysPrintf("LoadMcds()\r\n");
	LoadMcds(Config.Mcd1, Config.Mcd2);

	SysPrintf("end SysInit()\r\n");
	return 0;
}

void SysUpdate() {
}

void SysRunGui() {
}

void SysMessage(char *fmt, ...) {
}

void SysReset() {
    SysPrintf("start SysReset()\r\n");
	psxReset();
	SysPrintf("end SysReset()\r\n");
}

void SysClose() {
	psxShutdown();
	ReleasePlugins();
}

void *SysLoadLibrary(char *lib) {
	int i;
	SysPrintf("SysLoadLibrary %s\n",lib);
	for(i=0; i<NUM_PLUGINS; i++)
		if((plugins[i].lib != NULL) && (!strcmp(lib, plugins[i].lib)))
			return (void*)i;
	return NULL;
}

void *SysLoadSym(void *lib, char *sym) {
	PluginTable* plugin = plugins + (int)lib;
	int i;
	SysPrintf("SysLoadSym %s\n",sym);
	for(i=0; i<plugin->numSyms; i++)
		if(plugin->syms[i].sym && !strcmp(sym, plugin->syms[i].sym))
			return plugin->syms[i].pntr;
	return NULL;
}


void SysCloseLibrary(void *lib) {
//	dlclose(lib);
}

unsigned char SysMallocBuf[0x1000000];

void *SysMalloc(size_t size){
	static int lp=0;
	lp+=size;
	if(lp>sizeof(SysMallocBuf)){
		OutputDebugStringA("trop gros");
		DebugBreak();
		return NULL;
	}else{
		return &SysMallocBuf[lp-size];
	}
}

