#include "GlobalExtern.h"
extern int create_datfile(TCHAR* szFilename, int nDatType, int bIncMegadrive);

void InitROMSelectEditMenu() {
	if(TexPreview) {
		TexPreview->Release();
		TexPreview = NULL;
	}
	D3DXCreateTextureFromFileEx(Device, "D:\\media\\preview.png", D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexPreview);
	initMovie("D:\\media\\videopreview.xmv");
	GameInfoDetail.clear();
	GameInfoDetail.push_back("Street Fighter II - The World Warrior");
	GameInfoDetail.push_back("");
	GameInfoDetail.push_back("SF2 is the fighting game that changed the");
	GameInfoDetail.push_back("face of video-games forever. So");
	GameInfoDetail.push_back("innovative was the game, that many of the");
	GameInfoDetail.push_back("game-play elements that fighting fans");
}

void ExitROMSelectEditMenu() {
	if(TexPreview) {
		TexPreview->Release();
		TexPreview = NULL;
	}
	GameInfoDetail.clear();
	stopMovie();
}

void DrawROMSelectEditMenu() {
	Device->SetTexture(0,TexROMBrowser);
	DrawBackground();

	if(PreviewResize || PreviewBorderResize) {
		Device->SetTexture(0,TexPreview);
		MakeVertexListPreview();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetTexture(0,TexPreviewBorder);
		MakeVertexListPreviewBorder();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	}

	if(PreviewVerticalResize || PreviewBorderVerticalResize) {
		Device->SetTexture(0,TexPreview);
		MakeVertexListPreviewVertical();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetTexture(0,TexPreviewBorder);
		MakeVertexListPreviewBorderVertical();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	}

	if(AlternatePreviewResize || AlternatePreviewBorderResize) {
		Device->SetTexture(0,TexPreview);
		MakeVertexListAlternatePreview();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetTexture(0,TexPreviewBorder);
		MakeVertexListAlternatePreviewBorder();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	}

	if(AlternatePreviewVerticalResize || AlternatePreviewBorderVerticalResize) {
		Device->SetTexture(0,TexPreview);
		MakeVertexListAlternatePreviewVertical();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetTexture(0,TexPreviewBorder);
		MakeVertexListAlternatePreviewBorderVertical();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	}

	if(VideoResize || GUIState == 34) {
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		drawMovie();
		Device->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->SetTexture(0,TexVideoBorder);
		MakeVertexListVideoBorder();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	}

	if(DualVideoResize || DualVideoBorderResize || GUIState == 28 ||
		GUIState == 32 || GUIState == 44 || GUIState == 45) {
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		drawMovie();
		Device->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->SetTexture(0,TexVideoBorder);
		MakeVertexListDualVideoBorder();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	}

	Device->SetTexture(0,TexROMBorder);
	MakeVertexListROMBorder();
	Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	FontSetColour(0xFFFFFF00);
	for(int i = 0; i <  GameListCount; i++) {
		FontText(ConvertCharStringToWCHAR("Street Fighter II - The World Warrior"),
			GameListX, GameListY + (i * vSpace), GameListWidth);
		FontSetColour(0xFFFFFFFF);
	}

	Device->SetTexture(0,TexSelectedBorder);
	MakeVertexListSelectedBorder();
	Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	FontGUI(ConvertCharStringToWCHAR("Street Fighter II - The World Warrior"), MenuPosX, ROMPosY, 640);
	/*if(GameInfoResize || GUIState == 41) {
		Device->SetTexture(0,TexInfoBorderSimple);
		MakeVertexListInfoBorderSimple();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		std::string e;
		SetFontHeight(GameInfoFontSize);
		e = "ROM Name: sf2";
		DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY);
		e = "Manufacturer: Capcom";
		DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + GameInfoVSpace);
		e = "Released: 1991";
		DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 2 * GameInfoVSpace);
		e = "System: CPS1";
		DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 3 * GameInfoVSpace);
		e = "Genre: 2D Fighting";
		DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 4 * GameInfoVSpace);
		SetFontHeight(FontSize);
	}*/

	Device->SetTexture(0,TexAnimatedLogo);
	MakeVertexListAnimatedLogo(false);
	Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
	Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
}

void ResetAnimatedLogo() {
	zLeftAnimatedLogoTemp = zLeftAnimatedLogo;
	zRightAnimatedLogoTemp = zRightAnimatedLogo;
	zTopAnimatedLogoTemp = zTopAnimatedLogo;
	zBottomAnimatedLogoTemp = zBottomAnimatedLogo;
	lMoveROMBrowserLogo = -1 * distanceROMBrowserLogo;
	rMoveROMBrowserLogo = distanceROMBrowserLogo;
	tMoveROMBrowserLogo = distanceROMBrowserLogo;
	bMoveROMBrowserLogo = -1 * distanceROMBrowserLogo;
	cMoveROMBrowserLogo = 0;
	lastTimeROMBrowserLogo = 0;
}

void ClickSound() {
	if(!disableMenuSounds) {
		playEffect(1);
	}
}

void CancelSound() {
	if(!disableMenuSounds) {
		playEffect(0);
	}
}

void ConfirmSound() {
	if(!disableMenuSounds) {
		playEffect(2);
	}
}

void CyclePreview(int e) {
	CurrentArtwork += e;
	if(CurrentArtwork > 8) CurrentArtwork = 1;
	if(CurrentArtwork < 1) CurrentArtwork = 8;
	if(CurrentArtwork == 1) 
		OptionEmulationVideoValueItems[9] = "1";
	if(CurrentArtwork == 2) 
		OptionEmulationVideoValueItems[9] = "2";
	if(CurrentArtwork == 3) 
		OptionEmulationVideoValueItems[9] = "3";
	if(CurrentArtwork == 4) 
		OptionEmulationVideoValueItems[9] = "4";
	if(CurrentArtwork == 5) 
		OptionEmulationVideoValueItems[9] = "5";
	if(CurrentArtwork == 6) 
		OptionEmulationVideoValueItems[9] = "6";
	if(CurrentArtwork == 7) 
		OptionEmulationVideoValueItems[9] = "7";
	if(CurrentArtwork == 8) 
		OptionEmulationVideoValueItems[9] = "8";
}

DWORD WINAPI Mp3player_ThreadFunc( LPVOID lpParam ) { 
	float FPS ;
	unsigned int perfCurr[2] ;
	unsigned int perfPrev[2] ;
	QueryPerformanceCounter((union _LARGE_INTEGER *) perfPrev);

	while (1) {
		if(Emulation) return 0;
			do {
				if(Emulation) return 0;
				if(MovieEnabled && videoRender && (GUIState == 1 || GUIState == 2)) {
					m_mp3player.pause(TRUE);
				}
					
				QueryPerformanceCounter((union _LARGE_INTEGER *) perfCurr);

				if (perfCurr[0] != perfPrev[0]) {					
					FPS = (float) (m_performanceFreq[0])  / (float) (perfCurr[0] - perfPrev[0]);
				} 
				else {
					FPS = 200.0f ;
				}
				Sleep(1) ;
			} while ( FPS > 120 ) ;

			perfPrev[0] = perfCurr[0];

			m_mp3player.processReal() ;
		
	}
	return 0; 
}

void SaveDat() {
	create_datfile("D:\\tools\\ClrMAMEProArcadeWithGenesis.dat", 0, true);
	create_datfile("D:\\tools\\RomCenterArcadeWithGenesis.dat", 1, true);
	create_datfile("D:\\tools\\ClrMAMEProArcadeWithGenesis.xml", 2, true);
	create_datfile("D:\\tools\\ClrMAMEProArcadeWithoutGenesis.dat", 0, false);
	create_datfile("D:\\tools\\RomCenterArcadeWithoutGenesis.dat", 1, false);
	create_datfile("D:\\tools\\ClrMAMEProArcadeWithoutGenesis.xml", 2, false);
}

DWORD WINAPI Mp3player_ThreadFuncSplash( LPVOID lpParam ) { 
	float FPS ;
	unsigned int perfCurr[2] ;
	unsigned int perfPrev[2] ;
	QueryPerformanceCounter((union _LARGE_INTEGER *) perfPrev);

	while (1) {
		if(SplashFinshed) return 0;
			do {
				if(SplashFinshed) return 0;
				QueryPerformanceCounter((union _LARGE_INTEGER *) perfCurr);

				if (perfCurr[0] != perfPrev[0]) {					
					FPS = (float) (m_performanceFreqSplash[0])  / (float) (perfCurr[0] - perfPrev[0]);
				} 
				else {
					FPS = 200.0f ;
				}
				Sleep(1) ;
			} while ( FPS > 120 ) ;

			perfPrev[0] = perfCurr[0];

			m_mp3playerSplash.processReal() ;
		
	}
	return 0; 
}

string ConvertIntToString(int n) {
	char q[133];
	std::string e;
	for(int i = 0; i < 133; i++) 
		q[i] = '\0'; 
	itoa(n, q, 10); 
	e = q; 
	return e;
}

string ConvertFloatToString(float n) {
	std::ostringstream temp;
	temp << n;
	return temp.str();;
}

WCHAR* ConvertCharStringToWCHAR(char* q) {
	std::string t = q;
	for(int r = 0; r < 1024; r++) {
		if((t.c_str())[r] == '\0') {
			msg[r] = '\0';
			break;
		}
		msg[r] = (WCHAR)(t.c_str())[r];
	}
	return msg;
}

std::string GetFileString(FILE* f) {
	std::string e = "";
	char line[260];
	for(int i = 0; i < 260; i++) line[i] = '\0';
	fgets(line,260, f);
	for(int i = 0; i < 260; i++) {
		if(line[i] == '\n' || line[i] == '\0') {
			e += '\0';
			break;
		}
		e += line[i];
	}
	int temp = e.find("=", 0);
	if(temp != -1) {
		if(temp == (e.size() - 1))
			e = "";
		else
			e = e.substr(temp + 1, e.size() - temp);
	}
	//dprintf("GetFileString: %s\n", e.c_str());
	return e;
}

int GetFileInteger(FILE * f) {
	char line[100];
	fgets(line,100, f);
	for(int i = 0; i < 100; i++) {
		if(line[i] == '=') {
			return (int) atof(&line[i+1]);
		}
	}
	return -1;
}

float GetFileFloat(FILE * f) {
	char line[100];
	fgets(line,100, f);
	for(int i = 0; i < 100; i++) {
		if(line[i] == '=') {
			return atof(&line[i+1]);
		}
	}
	return -1;
}

void DisplayMessage(char* q) {
	Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
	Device->SetTexture(0,TexOption);
	DrawBackground();
	FontSetColour(0xffffff);
	FontCenteredText(ConvertCharStringToWCHAR(q), 320, 240, 640);
	Present();
}

void DisplayCenteredMsg(char* q, int y) {
	FontSetColour(0xffff00);
	FontCenteredText(ConvertCharStringToWCHAR(q),320,240, sWidth);
}

void DrawMsg(char* text, int x, int y) {
	FontSetColour(0xffffff);
	FontText(ConvertCharStringToWCHAR(text), x, y, sWidth);
}

void DrawGameInfoItem(char* text, int x, int y) {
	FontSetColour(0xffffff);
	FontText(ConvertCharStringToWCHAR(text), x, y, gameInfoListWidth);
}

int xS = 320;
int yS = 240;
float xMove = 1;
float yMove = 1;
extern float GetFontHeight();

void ResetScreenSaver() {
	QueryPerformanceCounter(&ScreenSaverDelay);
	ScreenSaverLastTimeDelay = (FLOAT)ScreenSaverDelay.QuadPart;
}

bool StartScreenSaver() {
	QueryPerformanceCounter(&ScreenSaverDelay);
	if((((FLOAT)ScreenSaverDelay.QuadPart) - ScreenSaverLastTimeDelay) >=
		(((FLOAT)ticksPerSecondDelay.QuadPart) * (screenSaverTime * 60))) {
		return true;
	}
	else {
		return false;
	}
}

bool ButtonPressed() {
	if((g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_DOWN) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_UP) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_LEFT) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_RIGHT) ||
	   (g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) ||
	   (g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) ||
	   (g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_BACK) ||
	   (g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_START) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_A) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_B) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_X) ||
	   (g_Gamepads[DefaultController].Event == XBGAMEPAD_Y) ||
	   (g_Gamepads[DefaultController].fX1 > 0) ||
	   (g_Gamepads[DefaultController].fX1 < 0) ||
	   (g_Gamepads[DefaultController].fY1 > 0) ||
	   (g_Gamepads[DefaultController].fY1 < 0) ||
	   (g_Gamepads[DefaultController].fX2 > 0) ||
	   (g_Gamepads[DefaultController].fX2 < 0) ||
	   (g_Gamepads[DefaultController].fY2 > 0) ||
	   (g_Gamepads[DefaultController].fY2 < 0) ||
	   (g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_LEFT_THUMB) ||
	   (g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_RIGHT_THUMB)) {
		return true;
	   }
	else {
		return false;
	}	
}

void ScreenSaver() {
	xS += xMove;
	yS += yMove;

	if(xS > 488) {
		xMove *= -1;
	}
	if(yS > 421) {
		yMove *= -1;
	}
	if(xS < 147) {
		xMove *= -1;
	}
	if(yS < 7) {
		yMove *= -1;
	}

	Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
	if(sWidth == 640)
		SetFontHeight(1.33);
	if(sWidth == 1280)
		SetFontHeight(2.66);
	if(sWidth == 1920)
		SetFontHeight(4);
	FontSetColour(0x4B4B4B);
	FontGUI(ConvertCharStringToWCHAR("Final Burn Legends"), xS, yS, 640);
	Device->Present(NULL,NULL,NULL,NULL);
}

void Present() {
	if(!ButtonPressed()) {
		if(StartScreenSaver()) {
			float oldFont = GetFontHeight();
			while(true) {
				ReadInput();
				if(ButtonPressed()) {
					SetFontHeight(oldFont);
					ResetScreenSaver();
					break;
				}
				ScreenSaver();
			}
		}
		else {
			Device->Present(NULL,NULL,NULL,NULL);
		}
	}
	else {
		ResetScreenSaver();
		Device->Present(NULL,NULL,NULL,NULL);
	}
}

void DrawGameInformationDetail() {
	if(GameInfoDetail.size() == 0) return;
	SetFontHeight(GameInfoDetailFontSize);
	int start = 0;
	if(GameInfoDetailSelected > (GameInfoDetailNumLines / 2) && (GameInfoDetail.size() > GameInfoDetailNumLines)) {
		start += (GameInfoDetailSelected  - (GameInfoDetailNumLines / 2));
	}
	if((GameInfoDetailSelected > ((GameInfoDetail.size()-1) - (GameInfoDetailNumLines / 2))) && (GameInfoDetail.size() > GameInfoDetailNumLines)) {
		start = (GameInfoDetail.size() - GameInfoDetailNumLines);
	}
	int e = 0;
	for(int i = start; i <  start + GameInfoDetailNumLines; i++) {
		if(i == GameInfoDetail.size()) return;
		FontSetColour(0xffffff);
		FontText(ConvertCharStringToWCHAR((char*)GameInfoDetail[i].c_str()),
			GameInfoDetailPosX, GameInfoDetailPosY + (e * GameInfoDetailVSpace), GameInfoDetailWidth);
		e++;
	}
	SetFontHeight(FontSize);
}

void DrawGameInformation() {	
	std::string e;
	SetFontHeight(GameInfoFontSize);
	e = "ROM Name: ";
	e += GameDatabase[GameSelected].name.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY);
	e = "Manufacturer: ";
	e += GameDatabase[GameSelected].manufacturer.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + GameInfoVSpace);
	e = "Released: ";
	e += GameDatabase[GameSelected].date.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 2 * GameInfoVSpace);
	e = "System: ";
	e += GameDatabase[GameSelected].system.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 3 * GameInfoVSpace);
	e = "Genre: ";
	e += GameDatabase[GameSelected].genre.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 4 * GameInfoVSpace);
	SetFontHeight(FontSize);
}

void DrawGameFavoriteInformation() {	
	std::string e;
	SetFontHeight(GameInfoFontSize);
	e = "ROM Name: ";
	e += FavoritesDatabase[GameFavoriteSelected].name.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY);
	e = "Manufacturer: ";
	e += FavoritesDatabase[GameFavoriteSelected].manufacturer.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + GameInfoVSpace);
	e = "Released: ";
	e += FavoritesDatabase[GameFavoriteSelected].date.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 2 * GameInfoVSpace);
	e = "System: ";
	e += FavoritesDatabase[GameFavoriteSelected].system.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 3 * GameInfoVSpace);
	e = "Genre: ";
	e += FavoritesDatabase[GameFavoriteSelected].genre.c_str();
	DrawGameInfoItem((char*)e.c_str(), GameInfoPosX, GameInfoPosY + 4 * GameInfoVSpace);
	SetFontHeight(FontSize);
}

void SaveGameIni(string e) {
	//////////dprintf("Save Start: %s\n", e.c_str());
	FILE* f;
	char fileName[260];
	for(int i = 0; i < 260; i++) fileName[i] = '\0';
	sprintf(fileName,"%s%s%s%s", IniPath.c_str(), "\\emulation\\", e.c_str(), ".ini");
	//////////dprintf("File: %s\n", fileName);
	f = fopen(fileName, "w+");
	if(!f) {
		//////////dprintf("SaveGameIni Error\n");
		//////////dprintf("Error opening %s\n", fileName);
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}
	//////////dprintf("Save Success: %s\n", fileName);
	//////////dprintf("zLeft\n");
	fprintf(f, "zLeft=%f\n", zLeft);
	//////////dprintf("zRight\n");
	fprintf(f, "zRight=%f\n", zRight);
	//////////dprintf("zTop\n");
	fprintf(f, "zTop=%f\n", zTop);
	//////////dprintf("zBottom\n");
	fprintf(f, "zBottom=%f\n", zBottom);
	//////////dprintf("SoftwareFilter\n");
	fprintf(f, "SoftwareFilter=%d\n", SoftwareFilter);
	//////////dprintf("HardwareFilter\n");
	fprintf(f, "HardwareFilter=%d\n", HardwareFilter);
	//////////dprintf("vsyncEnabled\n");
	fprintf(f, "vsyncEnabled=%d\n", vsyncEnabled);
	//////////dprintf("pixelRatio\n");
	fprintf(f, "pixelRatio=%d\n", pixelRatio);
	//////////dprintf("FlickerFilter\n");
	fprintf(f, "FlickerFilter=%d\n", FlickerFilter);
	//////////dprintf("Soften\n");
	fprintf(f, "Soften=%d\n", Soften);
	//////////dprintf("nAudDSPModule\n");
	fprintf(f, "nAudDSPModule=%d\n", nAudDSPModule);
	//////////dprintf("disableMenuSounds\n");
	fprintf(f, "disableMenuSounds=%d\n", disableMenuSounds);
	//////////dprintf("RotationDegrees\n");
	fprintf(f, "RotationDegrees=%f\n", RotationDegrees);
	fprintf(f, "CursorSpeed=%d\n", CursorSpeed);
	fprintf(f, "nInterpolation=%d\n", nInterpolation);
	fprintf(f, "nFMInterpolation=%d\n", nFMInterpolation);
	fprintf(f, "HiScoreSaving=%d\n", HiScoreSaving);
	fprintf(f, "DipEnabled=%d\n", DipEnabled);
	fprintf(f, "CPUSpeed=%d\n", CPUSpeed);
	fprintf(f, "neoGeoFree=%d\n", neoGeoFree);
	fprintf(f, "bAlwaysDrawFrames=%d\n", bAlwaysDrawFrames);
	fprintf(f, "SNKBIOS=%d\n", SNKBIOS);
	fprintf(f, "XBINPUT_DEADZONE=%f\n", XBINPUT_DEADZONE);
	//////////dprintf("fclose\n");
	fclose(f);
	//////////dprintf("Save End: %s\n", e.c_str());
}

void LoadGameIni(string e) {
	//////////dprintf("Load: %s\n", e.c_str());
	FILE* f;
	char fileName[260];
	for(int i = 0; i < 260; i++) fileName[i] = '\0';
	sprintf(fileName,"%s%s%s%s", IniPath.c_str(), "\\emulation\\", e.c_str(), ".ini");
	//////////dprintf("File: %s\n", fileName);
	f = fopen(fileName , "r");
	if(f) {
		//////////dprintf("Load Success: %s\n", fileName);
		zLeft = GetFileFloat(f);
		zRight = GetFileFloat(f);
		zTop = GetFileFloat(f);
		zBottom = GetFileFloat(f);
		SoftwareFilter = GetFileInteger(f);
		HardwareFilter = GetFileInteger(f);
		vsyncEnabled = GetFileInteger(f);
		pixelRatio = GetFileInteger(f);
		FlickerFilter = GetFileInteger(f);
		Soften = GetFileInteger(f);
		nAudDSPModule = GetFileInteger(f);
		disableMenuSounds = GetFileInteger(f);
		RotationDegrees = GetFileFloat(f);
		CursorSpeed = GetFileInteger(f);
		nInterpolation = GetFileInteger(f);
		nFMInterpolation = GetFileInteger(f);
		HiScoreSaving = GetFileInteger(f);
		DipEnabled = GetFileInteger(f);
		CPUSpeed = GetFileInteger(f);
		neoGeoFree = GetFileInteger(f);
		bAlwaysDrawFrames = GetFileInteger(f);
		SNKBIOS = (unsigned char) GetFileInteger(f);
		XBINPUT_DEADZONE = GetFileFloat(f); 
		
		if(HardwareFilter == 0)
			OptionEmulationVideoValueItems[0] = "None";
		if(HardwareFilter == 1)
			OptionEmulationVideoValueItems[0] = "Point";
		if(HardwareFilter == 2)
			OptionEmulationVideoValueItems[0] = "Bilinear";
		if(HardwareFilter == 3)
			OptionEmulationVideoValueItems[0] = "Trilinear";
		if(HardwareFilter == 4)
			OptionEmulationVideoValueItems[0] = "Anisotropic";
		if(HardwareFilter == 5)
			OptionEmulationVideoValueItems[0] = "Quincunx";
		if(HardwareFilter == 6)
			OptionEmulationVideoValueItems[0] = "Gaussian Cubic";
		if(SoftwareFilter == 0)
			OptionEmulationVideoValueItems[1] = "No Filter";
		if(SoftwareFilter == 1)
			OptionEmulationVideoValueItems[1] = "SuperScale2X";
		if(SoftwareFilter == 2)
			OptionEmulationVideoValueItems[1] = "AdvanceMame2X";
		if(SoftwareFilter == 3)
			OptionEmulationVideoValueItems[1] = "HQ2X";
		if(SoftwareFilter == 4)
			OptionEmulationVideoValueItems[1] = "Simple2X";
		if(SoftwareFilter == 5)
			OptionEmulationVideoValueItems[1] = "Scanline";
		if(SoftwareFilter == 6)
			OptionEmulationVideoValueItems[1] = "2xSaI";
		if(SoftwareFilter == 7)
			OptionEmulationVideoValueItems[1] = "Super2xSaI"; 
		if(SoftwareFilter == 8)
			OptionEmulationVideoValueItems[1] = "SuperEagle";
		if(SoftwareFilter == 9)
			OptionEmulationVideoValueItems[1] = "SuperScale75";
		
		if(FlickerFilter == 0)
			OptionEmulationVideoValueItems[2] = "0";
		if(FlickerFilter == 1)
			OptionEmulationVideoValueItems[2] = "1";
		if(FlickerFilter == 2)
			OptionEmulationVideoValueItems[2] = "2";
		if(FlickerFilter == 3)
			OptionEmulationVideoValueItems[2] = "3";
		if(FlickerFilter == 4)
			OptionEmulationVideoValueItems[2] = "4";
		if(FlickerFilter == 5)
			OptionEmulationVideoValueItems[2] = "5";
		
		if(Soften == 0)
			OptionEmulationVideoValueItems[3] = "Off";
		if(Soften == 1)
			OptionEmulationVideoValueItems[3] = "On";
		if(vsyncEnabled == 0)
			OptionEmulationVideoValueItems[5] = "Off";
		if(vsyncEnabled == 1)
			OptionEmulationVideoValueItems[5] = "On";
		if(dimColor == 1) 
			OptionEmulationVideoValueItems[6] = "On";
		if(dimColor == 0)
			OptionEmulationVideoValueItems[6] = "Off";
		if(pixelRatio == 1) 
			OptionEmulationVideoValueItems[7] = "On";
		if(pixelRatio == 0)
			OptionEmulationVideoValueItems[7] = "Off";
		if(RotationDegrees == 0) 
			OptionEmulationVideoValueItems[8] = "Disabled";
		if(RotationDegrees == 90) 
			OptionEmulationVideoValueItems[8] = "90 Degrees";
		if(RotationDegrees == 180) 
			OptionEmulationVideoValueItems[8] = "180 Degrees";
		if(RotationDegrees == 270) 
			OptionEmulationVideoValueItems[8] = "270 Degrees";

		if(nAudDSPModule == 0)
			OptionEmulationSoundValueItems[0] = "Off";
		else
			OptionEmulationSoundValueItems[0] = "On";
		if(disableMenuSounds == 0)
			OptionEmulationSoundValueItems[1] = "False";
		else
			OptionEmulationSoundValueItems[1] = "True";
		if(nInterpolation == 1)
			OptionEmulationSoundValueItems[2] = "Linear";
		else
			OptionEmulationSoundValueItems[2] = "Cubic";
		if(nFMInterpolation == 0)
			OptionEmulationSoundValueItems[3] = "Disabled";
		else
			OptionEmulationSoundValueItems[3] = "Enabled";

		if(HiScoreSaving == 1) 
			GeneralOptionsValueSettings[0] = "True";
		else
			GeneralOptionsValueSettings[0] = "False";

		if(DipEnabled == 1) 
			GeneralOptionsValueSettings[1] = "True";
		else
			GeneralOptionsValueSettings[1] = "False";

		std::ostringstream temp;
		temp << (float)(((float)CPUSpeed / 256) * 100) << "%";
		std::string temp2 = temp.str();
		GeneralOptionsValueSettings[2] = (char*)temp2.c_str();

		if(SNKBIOS == 0x00) GeneralOptionsValueSettings[3] = "MVS Asia/Europe ver. 6 (1 slot)";
		if(SNKBIOS == 0x01) GeneralOptionsValueSettings[3] = "MVS Asia/Europe ver. 5 (1 slot)";
		if(SNKBIOS == 0x02) GeneralOptionsValueSettings[3] = "MVS Asia/Europe ver. 3 (4 slot)";
		if(SNKBIOS == 0x03) GeneralOptionsValueSettings[3] = "MVS USA ver. 5 (2 slot)";
		if(SNKBIOS == 0x04) GeneralOptionsValueSettings[3] = "MVS USA ver. 5 (6 slot)";
		if(SNKBIOS == 0x05) GeneralOptionsValueSettings[3] = "MVS Japan ver. 6 (? slot)";
		if(SNKBIOS == 0x06) GeneralOptionsValueSettings[3] = "MVS Japan ver. 5 (? slot)";
		if(SNKBIOS == 0x07) GeneralOptionsValueSettings[3] = "MVS Japan ver. 3 (4 slot)";
		if(SNKBIOS == 0x08) GeneralOptionsValueSettings[3] = "NEO-MVH MV1C";
		if(SNKBIOS == 0x09) GeneralOptionsValueSettings[3] = "AES Japan";
		if(SNKBIOS == 0x0a) GeneralOptionsValueSettings[3] = "AES Asia";
		if(SNKBIOS == 0x0b) GeneralOptionsValueSettings[3] = "Development Kit";
		if(SNKBIOS == 0x0c) GeneralOptionsValueSettings[3] = "Deck ver. 6 (Git Ver 1.3)";
		if(SNKBIOS == 0x0d) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 2.3";
		if(SNKBIOS == 0x0e) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 2.3 (alt)";
		if(SNKBIOS == 0x0f) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 2.2";
		if(SNKBIOS == 0x10) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 2.1";
		if(SNKBIOS == 0x11) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 2.0";
		if(SNKBIOS == 0x12) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 1.3";
		if(SNKBIOS == 0x13) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 1.2";
		if(SNKBIOS == 0x14) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 1.2 (alt)";
		if(SNKBIOS == 0x15) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 1.1";
		if(SNKBIOS == 0x16) GeneralOptionsValueSettings[3] = "Universe BIOS ver. 1.0";

		if(neoGeoFree == 1) {
			GeneralOptionsValueSettings[4] = "Enabled";
		}
		else {
			GeneralOptionsValueSettings[4] = "Disabled";
		}

		std::ostringstream temp3;
		temp3 << XBINPUT_DEADZONE;
		std::string temp23 = temp3.str();
		GeneralOptionsValueSettings[5] = (char*)temp23.c_str();

		fclose(f);
	}
	else {
		//////////dprintf("Load Error: %s\n", fileName);
		SaveGameIni(e);
		LoadGameIni(e);
	}
}

void SaveIni() {
	FILE* f;
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\FinalBurnLegends.ini");
	f = fopen(fileName, "w+");
	if(!f) {
		//////////dprintf("SaveIni Error\n");
		//////////dprintf("Error opening %s\n", fileName);
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}
	//////////dprintf("SaveIni OK\n");
	fprintf(f, "GameListWidth=%d\n", GameListWidth);
	fprintf(f, "GameListX=%d\n", GameListX);
	fprintf(f, "GameListY=%d\n", GameListY);
	fprintf(f, "HDMode=%d\n", HDMode);
	fprintf(f, "vSpace=%d\n", vSpace);
	fprintf(f, "SoftwareFilter=%d\n", SoftwareFilter);
	fprintf(f, "HardwareFilter=%d\n", HardwareFilter);
	fprintf(f, "vsyncEnabled=%d\n", vsyncEnabled);
	fprintf(f, "dimColor=%d\n", dimColor);
	fprintf(f, "pixelRatio=%d\n", pixelRatio);
	fprintf(f, "FlickerFilter=%d\n", FlickerFilter);
	fprintf(f, "Soften=%d\n", Soften);
	fprintf(f, "scrollSpeed=%d\n", scrollSpeed);
	fprintf(f, "GameSelected=%d\n", GameSelected);
	fprintf(f, "GameFavoriteSelected=%d\n", GameFavoriteSelected);
	fprintf(f, "GameOptionPosX=%d\n", GameOptionPosX);
	fprintf(f, "GameOptionPosY=%d\n", GameOptionPosY);
	fprintf(f, "nAudDSPModule=%d\n", nAudDSPModule);
	fprintf(f, "nAudSampleRate=%d\n", nAudSampleRate);
	fprintf(f, "FontSize=%f\n", FontSize);
	fprintf(f, "GameListCount=%d\n", GameListCount);
	fprintf(f, "DefaultController=%d\n", DefaultController);
	fprintf(f, "MenuSpacing=%d\n", MenuSpacing);
	fprintf(f, "MainMenuPosY=%d\n", MainMenuPosY);
	fprintf(f, "MainMenuPosX=%d\n", MainMenuPosX);
	fprintf(f, "MainMenuVSpace=%d\n", MainMenuVSpace);
	fprintf(f, "MainMenuFontSize=%f\n", MainMenuFontSize);
	fprintf(f, "MainMenuCentered=%d\n", MainMenuCentered);
	fprintf(f, "MenuPosY=%d\n", MenuPosY);
	fprintf(f, "MenuPosX=%d\n", MenuPosX);
	fprintf(f, "MenuDetailPosX=%d\n", MenuDetailPosX);
	fprintf(f, "MenuDetailPosY=%d\n", MenuDetailPosY);
	fprintf(f, "ROMPosY=%d\n", ROMPosY);
	fprintf(f, "zLeftMenu=%f\n", zLeftMenu);
	fprintf(f, "zRightMenu=%f\n", zRightMenu);
	fprintf(f, "zTopMenu=%f\n", zTopMenu);
	fprintf(f, "zBottomMenu=%f\n", zBottomMenu);
	fprintf(f, "zLeftPreview=%f\n", zLeftPreview);
	fprintf(f, "zRightPreview=%f\n", zRightPreview);
	fprintf(f, "zTopPreview=%f\n", zTopPreview);
	fprintf(f, "zBottomPreview=%f\n", zBottomPreview);
	fprintf(f, "GameInfoPosX=%d\n", GameInfoPosX);
	fprintf(f, "GameInfoPosY=%d\n", GameInfoPosY);
	fprintf(f, "GameInfoFontSize=%f\n", GameInfoFontSize);
	fprintf(f, "GameInfoVSpace=%d\n", GameInfoVSpace);
	fprintf(f, "GameInfoDetailNumLines=%d\n", GameInfoDetailNumLines);
	fprintf(f, "GameInfoDetailPosX=%d\n", GameInfoDetailPosX);
	fprintf(f, "GameInfoDetailPosY=%d\n", GameInfoDetailPosY);
	fprintf(f, "GameInfoDetailFontSize=%f\n", GameInfoDetailFontSize);
	fprintf(f, "GameInfoDetailWidth=%d\n", GameInfoDetailWidth);
	fprintf(f, "GameInfoDetailVSpace=%d\n", GameInfoDetailVSpace);
	fprintf(f, "zoomSpeed=%d\n", zoomSpeed);
	fprintf(f, "gameInfoListWidth=%d\n", gameInfoListWidth);
	fprintf(f, "GameGuideLines=%d\n", GameGuideLines);
	fprintf(f, "GameGuideColor=%d\n", GameGuideColor);
	fprintf(f, "GameGuideFontSize=%f\n", GameGuideFontSize);
	fprintf(f, "guideLeft=%d\n", guideLeft);
	if(GUIState != ROM_SELECT && GUIState != FAVORITE_SELECT) 
		GUIState = MAIN_MENU;
	fprintf(f, "GUIState=%d\n", GUIState);
	fprintf(f, "fadeSpeed=%d\n", fadeSpeed);
	fprintf(f, "GameGuideWidth=%d\n", GameGuideWidth);
	fprintf(f, "GameGuideVSpace=%d\n", GameGuideVSpace);
	fprintf(f, "CustomSelected=%d\n", CustomSelected);
	fprintf(f, "CompanySelected=%d\n", CompanySelected);
	fprintf(f, "YearSelected=%d\n", YearSelected);
	fprintf(f, "GenreSelected=%d\n", GenreSelected);
	fprintf(f, "CustomSet=%d\n", CustomSet);
	fprintf(f, "CompanySet=%d\n", CompanySet);
	fprintf(f, "YearSet=%d\n", YearSet);
	fprintf(f, "GenreSet=%d\n", GenreSet);
	fprintf(f, "GameInfoEnabled=%d\n", GameInfoEnabled);
	fprintf(f, "GameInfoDetailEnabled=%d\n", GameInfoDetailEnabled);
	fprintf(f, "disableMenuSounds=%d\n", disableMenuSounds);
	fprintf(f, "fLeft=%f\n", fLeft);
	fprintf(f, "fRight=%f\n", fRight);
	fprintf(f, "fTop=%f\n", fTop);
	fprintf(f, "fBottom=%f\n", fBottom);
	fprintf(f, "fLeftMenu=%f\n", fLeftMenu);
	fprintf(f, "fRightMenu=%f\n", fRightMenu);
	fprintf(f, "fTopMenu=%f\n", fTopMenu);
	fprintf(f, "fBottomMenu=%f\n", fBottomMenu);
	fprintf(f, "zLeftPreviewBorder=%f\n", zLeftPreviewBorder);
	fprintf(f, "zRightPreviewBorder=%f\n", zRightPreviewBorder);
	fprintf(f, "zTopPreviewBorder=%f\n", zTopPreviewBorder);
	fprintf(f, "zBottomPreviewBorder=%f\n", zBottomPreviewBorder);
	fprintf(f, "zLeftInfoBorder=%f\n", zLeftInfoBorder);
	fprintf(f, "zRightInfoBorder=%f\n", zRightInfoBorder);
	fprintf(f, "zTopInfoBorder=%f\n", zTopInfoBorder);
	fprintf(f, "zBottomInfoBorder=%f\n", zBottomInfoBorder);
	fprintf(f, "zLeftVideoBorder=%f\n", zLeftVideoBorder);
	fprintf(f, "zRightVideoBorder=%f\n", zRightVideoBorder);
	fprintf(f, "zTopVideoBorder=%f\n", zTopVideoBorder);
	fprintf(f, "zBottomVideoBorder=%f\n", zBottomVideoBorder);
	fprintf(f, "zLeftROMBorder=%f\n", zLeftROMBorder);
	fprintf(f, "zRightROMBorder=%f\n", zRightROMBorder);
	fprintf(f, "zTopROMBorder=%f\n", zTopROMBorder);
	fprintf(f, "zBottomROMBorder=%f\n", zBottomROMBorder);
	fprintf(f, "zLeftSelectBorder=%f\n", zLeftSelectBorder);
	fprintf(f, "zRightSelectBorder=%f\n", zRightSelectBorder);
	fprintf(f, "zTopSelectBorder=%f\n", zTopSelectBorder);
	fprintf(f, "zBottomSelectBorder=%f\n", zBottomSelectBorder);
	fprintf(f, "zLeftAlternatePreview=%f\n", zLeftAlternatePreview);
	fprintf(f, "zRightAlternatePreview=%f\n", zRightAlternatePreview);
	fprintf(f, "zTopAlternatePreview=%f\n", zTopAlternatePreview);
	fprintf(f, "zBottomAlternatePreview=%f\n", zBottomAlternatePreview);
	fprintf(f, "zLeftAlternatePreviewBorder=%f\n", zLeftAlternatePreviewBorder);
	fprintf(f, "zRightAlternatePreviewBorder=%f\n", zRightAlternatePreviewBorder);
	fprintf(f, "zTopAlternatePreviewBorder=%f\n", zTopAlternatePreviewBorder);
	fprintf(f, "zBottomAlternatePreviewBorder=%f\n", zBottomAlternatePreviewBorder);
	fprintf(f, "zLeftAnimatedLogo=%f\n", zLeftAnimatedLogo);
	fprintf(f, "zRightAnimatedLogo=%f\n", zRightAnimatedLogo);
	fprintf(f, "zTopAnimatedLogo=%f\n", zTopAnimatedLogo);
	fprintf(f, "zBottomAnimatedLogo=%f\n", zBottomAnimatedLogo);
	fprintf(f, "speedROMBrowserLogo=%f\n", speedROMBrowserLogo);
	fprintf(f, "distanceROMBrowserLogo=%f\n", distanceROMBrowserLogo);
	fprintf(f, "zLeftAnimatedLogoMainMenu=%f\n", zLeftAnimatedLogoMainMenu);
	fprintf(f, "zRightAnimatedLogoMainMenu=%f\n", zRightAnimatedLogoMainMenu);
	fprintf(f, "zTopAnimatedLogoMainMenu=%f\n", zTopAnimatedLogoMainMenu);
	fprintf(f, "zBottomAnimatedLogoMainMenu=%f\n", zBottomAnimatedLogoMainMenu);
	fprintf(f, "speedLogoMainMenu=%f\n", speedLogoMainMenu);
	fprintf(f, "distanceLogoMainMenu=%f\n", distanceLogoMainMenu);
	fprintf(f, "zLeftInfoBorderSimple=%f\n", zLeftInfoBorderSimple);
	fprintf(f, "zRightInfoBorderSimple=%f\n", zRightInfoBorderSimple);
	fprintf(f, "zTopInfoBorderSimple=%f\n", zTopInfoBorderSimple);
	fprintf(f, "zBottomInfoBorderSimple=%f\n", zBottomInfoBorderSimple);
	fprintf(f, "BackgroundMusicVolume=%d\n", BackgroundMusicVolume);
	fprintf(f, "%s\n", SkinPath.c_str());
	fprintf(f, "zLeftPreviewVertical=%f\n", zLeftPreviewVertical);
	fprintf(f, "zRightPreviewVertical=%f\n", zRightPreviewVertical);
	fprintf(f, "zTopPreviewVertical=%f\n", zTopPreviewVertical);
	fprintf(f, "zBottomPreviewVertical=%f\n", zBottomPreviewVertical);
	fprintf(f, "zLeftPreviewBorderVertical=%f\n", zLeftPreviewBorderVertical);
	fprintf(f, "zRightPreviewBorderVertical=%f\n", zRightPreviewBorderVertical);
	fprintf(f, "zTopPreviewBorderVertical=%f\n", zTopPreviewBorderVertical);
	fprintf(f, "zBottomPreviewBorderVertical=%f\n", zBottomPreviewBorderVertical);
	fprintf(f, "zLeftAlternatePreviewVertical=%f\n", zLeftAlternatePreviewVertical);
	fprintf(f, "zRightAlternatePreviewVertical=%f\n", zRightAlternatePreviewVertical);
	fprintf(f, "zTopAlternatePreviewVertical=%f\n", zTopAlternatePreviewVertical);
	fprintf(f, "zBottomAlternatePreviewVertical=%f\n", zBottomAlternatePreviewVertical);
	fprintf(f, "zLeftAlternatePreviewBorderVertical=%f\n", zLeftAlternatePreviewBorderVertical);
	fprintf(f, "zRightAlternatePreviewBorderVertical=%f\n", zRightAlternatePreviewBorderVertical);
	fprintf(f, "zTopAlternatePreviewBorderVertical=%f\n", zTopAlternatePreviewBorderVertical);
	fprintf(f, "zBottomAlternatePreviewBorderVertical=%f\n", zBottomAlternatePreviewBorderVertical);
	fprintf(f, "ScrollSpeed=%d\n", ScrollSpeed);
	fprintf(f, "nInterpolation=%d\n", nInterpolation);
	fprintf(f, "nFMInterpolation=%d\n", nFMInterpolation);
	fprintf(f, "zLeft0=%f\n", zLeft0);
	fprintf(f, "zRight0=%f\n", zRight0);
	fprintf(f, "zTop0=%f\n", zTop0); 
	fprintf(f, "zBottom0=%f\n", zBottom0);
	fprintf(f, "zLeft90=%f\n", zLeft90);
	fprintf(f, "zRight90=%f\n", zRight90);
	fprintf(f, "zTop90=%f\n", zTop90);
	fprintf(f, "zBottom90=%f\n", zBottom90);
	fprintf(f, "zLeft180=%f\n", zLeft180);
	fprintf(f, "zRight180=%f\n", zRight180);
	fprintf(f, "zTop180=%f\n", zTop180);
	fprintf(f, "zBottom180=%f\n", zBottom180);
	fprintf(f, "zLeft270=%f\n", zLeft270);
	fprintf(f, "zRight270=%f\n", zRight270);
	fprintf(f, "zTop270=%f\n", zTop270);
	fprintf(f, "zBottom270=%f\n", zBottom270);
	fprintf(f, "zLeftMainMenuOverlay1=%f\n", zLeftMainMenuOverlay1);
	fprintf(f, "zRightMainMenuOverlay1=%f\n", zRightMainMenuOverlay1);
	fprintf(f, "zTopMainMenuOverlay1=%f\n", zTopMainMenuOverlay1);
	fprintf(f, "zBottomMainMenuOverlay1=%f\n", zBottomMainMenuOverlay1);
	fprintf(f, "zLeftMainMenuOverlay2=%f\n", zLeftMainMenuOverlay2);
	fprintf(f, "zRightMainMenuOverlay2=%f\n", zRightMainMenuOverlay2);
	fprintf(f, "zTopMainMenuOverlay2=%f\n", zTopMainMenuOverlay2);
	fprintf(f, "zBottomMainMenuOverlay2=%f\n", zBottomMainMenuOverlay2);
	fprintf(f, "zLeftMainMenuOverlay3=%f\n", zLeftMainMenuOverlay3);
	fprintf(f, "zRightMainMenuOverlay3=%f\n", zRightMainMenuOverlay3);
	fprintf(f, "zTopMainMenuOverlay3=%f\n", zTopMainMenuOverlay3);
	fprintf(f, "zBottomMainMenuOverlay3=%f\n", zBottomMainMenuOverlay3);
	fprintf(f, "zLeftMainMenuOverlay4=%f\n", zLeftMainMenuOverlay4);
	fprintf(f, "zRightMainMenuOverlay4=%f\n", zRightMainMenuOverlay4);
	fprintf(f, "zTopMainMenuOverlay4=%f\n", zTopMainMenuOverlay4);
	fprintf(f, "zBottomMainMenuOverlay4=%f\n", zBottomMainMenuOverlay4);
	fprintf(f, "zLeftMainMenuOverlay5=%f\n", zLeftMainMenuOverlay5);
	fprintf(f, "zRightMainMenuOverlay5=%f\n", zRightMainMenuOverlay5);
	fprintf(f, "zTopMainMenuOverlay5=%f\n", zTopMainMenuOverlay5);
	fprintf(f, "zBottomMainMenuOverlay5=%f\n", zBottomMainMenuOverlay5);
	fprintf(f, "zLeftMainMenuOverlay6=%f\n", zLeftMainMenuOverlay6);
	fprintf(f, "zRightMainMenuOverlay6=%f\n", zRightMainMenuOverlay6);
	fprintf(f, "zTopMainMenuOverlay6=%f\n", zTopMainMenuOverlay6);
	fprintf(f, "zBottomMainMenuOverlay6=%f\n", zBottomMainMenuOverlay6);
	fprintf(f, "fDualLeft=%f\n", fDualLeft);
	fprintf(f, "fDualRight=%f\n", fDualRight);
	fprintf(f, "fDualTop=%f\n", fDualTop);
	fprintf(f, "fDualBottom=%f\n", fDualBottom);
	fprintf(f, "zLeftDualVideoBorder=%f\n", zLeftDualVideoBorder);
	fprintf(f, "zRightDualVideoBorder=%f\n", zRightDualVideoBorder);
	fprintf(f, "zTopDualVideoBorder=%f\n", zTopDualVideoBorder);
	fprintf(f, "zBottomDualVideoBorder=%f\n", zBottomDualVideoBorder);
	fprintf(f, "screenSaverTime=%d\n", screenSaverTime);
	fprintf(f, "MovieEnabled=%d\n", MovieEnabled);
	fprintf(f, "DisplayMode=%d\n", DisplayMode);
	fprintf(f, "HighlightParent=%d\n", HighlightParent);
	fprintf(f, "PauseGame=%d\n", PauseGame);
	fprintf(f, "MainMenuMovieSwitchEnabled=%d\n", MainMenuMovieSwitchEnabled);
	fprintf(f, "MainMenuVideoPath0=%s\n", (char*)MainMenuVideoPath0.c_str());
	fprintf(f, "MainMenuVideoPath1=%s\n", (char*)MainMenuVideoPath1.c_str());
	fprintf(f, "MainMenuVideoPath2=%s\n", (char*)MainMenuVideoPath2.c_str());
	fprintf(f, "MainMenuVideoPath3=%s\n", (char*)MainMenuVideoPath3.c_str());
	fprintf(f, "MainMenuVideoPath4=%s\n", (char*)MainMenuVideoPath4.c_str());
	fprintf(f, "MainMenuVideoPath5=%s\n", (char*)MainMenuVideoPath5.c_str());
	fclose(f);
}

void SetParameters(FILE* f) {
	GameListWidth = GetFileInteger(f);
	GameListX = GetFileInteger(f);
	GameListY = GetFileInteger(f);
	HDMode = GetFileInteger(f);
	vSpace = GetFileInteger(f);
	SoftwareFilter = GetFileInteger(f);
	HardwareFilter = GetFileInteger(f);
	vsyncEnabled = GetFileInteger(f);
	dimColor = GetFileInteger(f);
	pixelRatio = GetFileInteger(f);
	FlickerFilter = GetFileInteger(f);
	Soften = GetFileInteger(f);
	scrollSpeed = GetFileInteger(f);
	GameSelected = GetFileInteger(f);
	GameFavoriteSelected = GetFileInteger(f);
	GameOptionPosX = GetFileInteger(f);
	GameOptionPosY = GetFileInteger(f);
	nAudDSPModule = GetFileInteger(f);
	nAudSampleRate = GetFileInteger(f);
	FontSize = GetFileFloat(f);
	GameListCount = GetFileInteger(f);
	DefaultController = GetFileInteger(f);
	MenuSpacing = GetFileInteger(f);
	MainMenuPosY = GetFileInteger(f);
	MainMenuPosX = GetFileInteger(f);
	MainMenuVSpace = GetFileInteger(f);
	MainMenuFontSize = GetFileFloat(f);
	MainMenuCentered = GetFileInteger(f);
	MenuPosY = GetFileInteger(f);
	MenuPosX = GetFileInteger(f);
	MenuDetailPosX = GetFileInteger(f);
	MenuDetailPosY = GetFileInteger(f);
	ROMPosY = GetFileInteger(f);
	zLeftMenu = GetFileFloat(f);
	zRightMenu = GetFileFloat(f);
	zTopMenu = GetFileFloat(f);
	zBottomMenu = GetFileFloat(f);
	zLeftPreview = GetFileFloat(f);
	zRightPreview = GetFileFloat(f);
	zTopPreview = GetFileFloat(f);
	zBottomPreview = GetFileFloat(f);
	GameInfoPosX = GetFileInteger(f);
	GameInfoPosY = GetFileInteger(f);
	GameInfoFontSize = GetFileFloat(f);
	GameInfoVSpace = GetFileInteger(f);
	GameInfoDetailNumLines = GetFileInteger(f);
	GameInfoDetailPosX = GetFileInteger(f);
	GameInfoDetailPosY = GetFileInteger(f);
	GameInfoDetailFontSize = GetFileFloat(f);
	GameInfoDetailWidth = GetFileInteger(f);
	GameInfoDetailVSpace = GetFileInteger(f);
	zoomSpeed = GetFileInteger(f);
	gameInfoListWidth = GetFileInteger(f);
	GameGuideLines = GetFileInteger(f);
	if(GameGuideLines > 21)
		GameGuideLines = 21;
	GameGuideColor = GetFileInteger(f);
	GameGuideFontSize = GetFileFloat(f);
	guideLeft = GetFileInteger(f);
	GUIState = GetFileInteger(f);
	fadeSpeed = GetFileInteger(f);
	GameGuideWidth = GetFileInteger(f);
	GameGuideVSpace = GetFileInteger(f);
	CustomSelected  = GetFileInteger(f);
	CompanySelected = GetFileInteger(f);
	YearSelected = GetFileInteger(f);
	GenreSelected = GetFileInteger(f);
	CustomSet = GetFileInteger(f);
	CompanySet = GetFileInteger(f);
	YearSet = GetFileInteger(f);
	GenreSet = GetFileInteger(f);
	GameInfoEnabled = GetFileInteger(f);
	GameInfoDetailEnabled = GetFileInteger(f);
	disableMenuSounds = GetFileInteger(f);
	fLeft = GetFileFloat(f);
	fRight = GetFileFloat(f);
	fTop = GetFileFloat(f);
	fBottom = GetFileFloat(f);
	fLeftMenu = GetFileFloat(f);
	fRightMenu = GetFileFloat(f);
	fTopMenu = GetFileFloat(f);
	fBottomMenu = GetFileFloat(f);
	zLeftPreviewBorder = GetFileFloat(f);
	zRightPreviewBorder = GetFileFloat(f);
	zTopPreviewBorder = GetFileFloat(f);
	zBottomPreviewBorder = GetFileFloat(f);
	zLeftInfoBorder = GetFileFloat(f);
	zRightInfoBorder = GetFileFloat(f);
	zTopInfoBorder = GetFileFloat(f);
	zBottomInfoBorder = GetFileFloat(f);
	zLeftVideoBorder = GetFileFloat(f);
	zRightVideoBorder = GetFileFloat(f);
	zTopVideoBorder = GetFileFloat(f);
	zBottomVideoBorder = GetFileFloat(f);
	zLeftROMBorder = GetFileFloat(f);
	zRightROMBorder = GetFileFloat(f);
	zTopROMBorder = GetFileFloat(f);
	zBottomROMBorder = GetFileFloat(f);
	zLeftSelectBorder = GetFileFloat(f);
	zRightSelectBorder = GetFileFloat(f);
	zTopSelectBorder = GetFileFloat(f);
	zBottomSelectBorder = GetFileFloat(f);
	zLeftAlternatePreview = GetFileFloat(f);
	zRightAlternatePreview = GetFileFloat(f);
	zTopAlternatePreview = GetFileFloat(f);
	zBottomAlternatePreview = GetFileFloat(f);
	zLeftAlternatePreviewBorder = GetFileFloat(f);
	zRightAlternatePreviewBorder = GetFileFloat(f);
	zTopAlternatePreviewBorder = GetFileFloat(f);
	zBottomAlternatePreviewBorder = GetFileFloat(f);
	zLeftAnimatedLogo = GetFileFloat(f);
	zRightAnimatedLogo = GetFileFloat(f);
	zTopAnimatedLogo = GetFileFloat(f);
	zBottomAnimatedLogo = GetFileFloat(f);
	speedROMBrowserLogo = GetFileFloat(f);
	distanceROMBrowserLogo = GetFileFloat(f);
	zLeftAnimatedLogoMainMenu = GetFileFloat(f);
	zRightAnimatedLogoMainMenu = GetFileFloat(f);
	zTopAnimatedLogoMainMenu = GetFileFloat(f);
	zBottomAnimatedLogoMainMenu = GetFileFloat(f);
	speedLogoMainMenu = GetFileFloat(f);
	distanceLogoMainMenu = GetFileFloat(f);
	zLeftInfoBorderSimple = GetFileFloat(f);
	zRightInfoBorderSimple = GetFileFloat(f);
	zTopInfoBorderSimple = GetFileFloat(f);
	zBottomInfoBorderSimple = GetFileFloat(f);
	BackgroundMusicVolume = GetFileInteger(f);
	SkinPath = GetFileString(f);
	zLeftPreviewVertical = GetFileFloat(f);
	zRightPreviewVertical = GetFileFloat(f);
	zTopPreviewVertical = GetFileFloat(f);
	zBottomPreviewVertical = GetFileFloat(f);
	zLeftPreviewBorderVertical = GetFileFloat(f);
	zRightPreviewBorderVertical = GetFileFloat(f);
	zTopPreviewBorderVertical = GetFileFloat(f);
	zBottomPreviewBorderVertical = GetFileFloat(f);
	zLeftAlternatePreviewVertical = GetFileFloat(f);
	zRightAlternatePreviewVertical = GetFileFloat(f);
	zTopAlternatePreviewVertical = GetFileFloat(f);
	zBottomAlternatePreviewVertical = GetFileFloat(f);
	zLeftAlternatePreviewBorderVertical = GetFileFloat(f);
	zRightAlternatePreviewBorderVertical = GetFileFloat(f);
	zTopAlternatePreviewBorderVertical = GetFileFloat(f);
	zBottomAlternatePreviewBorderVertical = GetFileFloat(f);
	ScrollSpeed = GetFileInteger(f);
	nInterpolation = GetFileInteger(f);
	nFMInterpolation = GetFileInteger(f);
	zLeft0 = GetFileFloat(f);
	zRight0 = GetFileFloat(f);
	zTop0 = GetFileFloat(f);
	zBottom0 = GetFileFloat(f);
	zLeft90 = GetFileFloat(f);
	zRight90 = GetFileFloat(f);
	zTop90 = GetFileFloat(f);
	zBottom90 = GetFileFloat(f);
	zLeft180 = GetFileFloat(f);
	zRight180 = GetFileFloat(f);
	zTop180 = GetFileFloat(f);
	zBottom180 = GetFileFloat(f);
	zLeft270 = GetFileFloat(f);
	zRight270 = GetFileFloat(f);
	zTop270 = GetFileFloat(f);
	zBottom270 = GetFileFloat(f);
	zLeftMainMenuOverlay1 = GetFileFloat(f);
	zRightMainMenuOverlay1 = GetFileFloat(f);
	zTopMainMenuOverlay1 = GetFileFloat(f);
	zBottomMainMenuOverlay1 = GetFileFloat(f);
	zLeftMainMenuOverlay2 = GetFileFloat(f);
	zRightMainMenuOverlay2 = GetFileFloat(f);
	zTopMainMenuOverlay2 = GetFileFloat(f);
	zBottomMainMenuOverlay2 = GetFileFloat(f);
	zLeftMainMenuOverlay3 = GetFileFloat(f);
	zRightMainMenuOverlay3 = GetFileFloat(f);
	zTopMainMenuOverlay3 = GetFileFloat(f);
	zBottomMainMenuOverlay3 = GetFileFloat(f);
	zLeftMainMenuOverlay4 = GetFileFloat(f);
	zRightMainMenuOverlay4 = GetFileFloat(f);
	zTopMainMenuOverlay4 = GetFileFloat(f);
	zBottomMainMenuOverlay4 = GetFileFloat(f);
	zLeftMainMenuOverlay5 = GetFileFloat(f);
	zRightMainMenuOverlay5 = GetFileFloat(f);
	zTopMainMenuOverlay5 = GetFileFloat(f);
	zBottomMainMenuOverlay5 = GetFileFloat(f);
	zLeftMainMenuOverlay6 = GetFileFloat(f);
	zRightMainMenuOverlay6 = GetFileFloat(f);
	zTopMainMenuOverlay6 = GetFileFloat(f);
	zBottomMainMenuOverlay6 = GetFileFloat(f);
	fDualLeft = GetFileFloat(f);
	fDualRight = GetFileFloat(f);
	fDualTop = GetFileFloat(f);
	fDualBottom = GetFileFloat(f);
	zLeftDualVideoBorder = GetFileFloat(f);
	zRightDualVideoBorder = GetFileFloat(f);
	zTopDualVideoBorder = GetFileFloat(f);
	zBottomDualVideoBorder = GetFileFloat(f);
	screenSaverTime = GetFileInteger(f);
	MovieEnabled = GetFileInteger(f);
	DisplayMode = GetFileInteger(f);
	HighlightParent = GetFileInteger(f);
	PauseGame = GetFileInteger(f);
	MainMenuMovieSwitchEnabled = GetFileInteger(f);
	MainMenuVideoPath0 = GetFileString(f);
	MainMenuVideoPath1 = GetFileString(f);
	MainMenuVideoPath2 = GetFileString(f);
	MainMenuVideoPath3 = GetFileString(f);
	MainMenuVideoPath4 = GetFileString(f);
	MainMenuVideoPath5 = GetFileString(f);

	dprintf("After Read MainMenuVideoPath0=%s\n", (char*)MainMenuVideoPath0.c_str());
	dprintf("After Read MainMenuVideoPath1=%s\n", (char*)MainMenuVideoPath1.c_str());
	dprintf("After Read MainMenuVideoPath2=%s\n", (char*)MainMenuVideoPath2.c_str());
	dprintf("After Read MainMenuVideoPath3=%s\n", (char*)MainMenuVideoPath3.c_str());
	dprintf("After Read MainMenuVideoPath4=%s\n", (char*)MainMenuVideoPath4.c_str());
	dprintf("After Read MainMenuVideoPath5=%s\n", (char*)MainMenuVideoPath5.c_str());
	if(PauseGame < 0 || PauseGame > 4)
		PauseGame = 0;
}

void LoadSkinIni(std::string skin) {
	//////////dprintf("Load skin ini\n");
	FILE* f;
	char fileName[260];
	sprintf(fileName,"%s%s%s%s%s", "D:\\skins\\", skin.c_str(), "\\", skin.c_str(), ".ini");
	f = fopen(fileName, "r");
	if(!f) {
		//////////dprintf("LoadSkinIni Error\n");
		//////////dprintf("Error opening %s\n", fileName);
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}
	//////////dprintf("Load skin ini ok\n");
	SetParameters(f);
	GameSelected = 0;
	GameFavoriteSelected = 0;
	CustomSelected = 0;
	CompanySelected = 0;
	YearSelected = 0;
	GenreSelected = 0;
	GUIState = 0;
	DisplayMode = 2;
	HighlightParent = 0; 
	MenuSelected = 0;
	fclose(f);
	//////////dprintf("LoadSkinIni End\n");
}

void LoadIni() {
	FILE* f;
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\FinalBurnLegends.ini");
	f = fopen(fileName, "r");
	if(!f) {
		string e = "arcade";
		LoadSkinIni(e);
		SaveIni();
		return;
	}
	SetParameters(f);
	fclose(f);
}

void ReturnToGUI() {
	if(CommandLineLaunch == 1) {
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}
	else {
		DisplayMessage("Please wait...");
		Device->PersistDisplay();
		PLAUNCH_DATA ldata ;
		memset( &ldata, 0, sizeof(PLAUNCH_DATA) ) ;
		XLaunchNewImage( "D:\\default.xbe", ldata ) ;
	}
}

void ROMError(char* msg) {
	OptionScreen();
	while(1) {
		updateEffect();
		ReadInput();
		if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
			ReturnToGUI();
		}
		FontSetColour(0xffff00);
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexOption);
		DrawBackground();
		FontGUI(ConvertCharStringToWCHAR(msg), 320, 240, 640);
		FontGUI(ConvertCharStringToWCHAR("Press \"A\" to exit"), 320, 240 + vSpace, 640);
		Present();
	}
}

void FBACrashed() {
	while(1) {
		ReadInput();
		if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
			ReturnToGUI();
		}
		FontSetColour(0xffff00);
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexOption);
		SetupMatrices();
		MakeVertexListMenu();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		FontGUI(ConvertCharStringToWCHAR((char*)"Final Burn Legends encountered a problem"), 320, 240, 640);
		FontGUI(ConvertCharStringToWCHAR((char*)"Press \"A\" to exit"), 320, 240 + vSpace, 640);
		Present();
	}
}

void OutOfMemory() {
	while(1) {
		updateEffect();
		ReadInput();
		if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
			ReturnToGUI();
		}
		FontSetColour(0xffff00);
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexOption);
		DrawBackground();
		FontGUI(ConvertCharStringToWCHAR((char*)"Out of Memory."), 320, 240, 640);
		FontGUI(ConvertCharStringToWCHAR((char*)"Press \"A\" to exit"), 320, 240 + vSpace, 640);
		Present();
	}
}

float freeMemory() {
	MEMORYSTATUS stat;
	GlobalMemoryStatus( &stat );
	return (((float)stat.dwAvailPhys) / 1024000);
}

void* osd_malloc(int n) {
	float q = n;
	q = q / 1024000.0f;
	//////////dprintf("Memory request: %f, Available: %f\n", q, freeMemory());
	float memory = freeMemory();
	if(q > memory || (memory < ((1024 * 1024 * 1) / 1024000))) {
		SaveIni();
		OutOfMemory();
	}
	else {
		return malloc(n);
	}
}

int PreviewSwitchValid() {
	QueryPerformanceCounter(&tickPreviewSwitch);
	if((((FLOAT)tickPreviewSwitch.QuadPart) - lastTimePreviewSwitch) >=
		(((FLOAT)ticksPerSecondPreviewSwitch.QuadPart) * 0.4)) {
		lastTimePreviewSwitch = (FLOAT)tickPreviewSwitch.QuadPart;
		return 1;
	}
	else {
		return 0;
	}
}

int AnimateROMBrowserLogoTimer() {
	QueryPerformanceCounter(&tickROMBrowserLogo);
	if(lastTimeROMBrowserLogo == 0) {
		lastTimeROMBrowserLogo = (FLOAT)tickROMBrowserLogo.QuadPart;
		return 0;
	}
	if((((FLOAT)tickROMBrowserLogo.QuadPart) - lastTimeROMBrowserLogo) >=
		(((FLOAT)ticksPerSecondROMBrowserLogo.QuadPart) / 60.0f) * 1) {
		lastTimeROMBrowserLogo = (FLOAT)tickROMBrowserLogo.QuadPart;
		return 1;
	}
	else {
		return 0;
	}
}

void SetDelay() {
	QueryPerformanceCounter(&tickDelay);
	lastTimeDelay = (FLOAT)tickDelay.QuadPart;
}

void SetDelayGuwange() {
	QueryPerformanceCounter(&tickDelay);
	lastTimeDelay = (FLOAT)tickDelay.QuadPart;
}

int DelayValidGuwange() {
	if(!delay) return 1;
	QueryPerformanceCounter(&tickDelay);
	if((((FLOAT)tickDelay.QuadPart) - lastTimeDelay) >=
		(((FLOAT)ticksPerSecondDelay.QuadPart) * 14)) {
		delay = false;
		return 1;
	}
	else {
		return 0;
	}
}

int DelayValid() {
	if(delay) {
		return DelayValidGuwange();
	}
	QueryPerformanceCounter(&tickDelay);
	if((((FLOAT)tickDelay.QuadPart) - lastTimeDelay) >=
		(((FLOAT)ticksPerSecondDelay.QuadPart) * 0.2)) {
		return 1;
	}
	else {
		return 0;
	}
}

int AnimateSplashScreen() {
	QueryPerformanceCounter(&tickSplashScreen);
	if((((FLOAT)tickSplashScreen.QuadPart) - lastTimeSplashScreen) >=
		(((FLOAT)ticksPerSecondSplashScreen.QuadPart) * 4)) {
		return 1;
	}
	else {
		return 0;
	}
}

void SplashScreen() {
	char fileName[260];
	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\splashscreen.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexSplashScreen);
	Device->CreateVertexBuffer(sizeof(VertexListSplashScreen),0,
		D3DFVF_CUSTOMVERTEX,D3DPOOL_DEFAULT,&VertexBufferSplashScreen);	
	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\splashscreen2.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexPreview);

	m_mp3playerSplash.dsound_init() ;
	m_mp3playerSplash.m_fps = 60;
	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\splash.mp3");
	m_mp3playerSplash.loadFile(fileName, 0, 0, 70*60*75 );
	//m_mp3playerSplash.insertSilence( 22050 );
	m_mp3playerSplash.pause( FALSE );
	m_mp3playerSplash.adjust_volume(BackgroundMusicVolume);
	memset( m_mp3playerSplash.m_pSoundBufferData, 0, m_mp3playerSplash.stream_buffer_size);
	for(int i = 0; i < 90; i++) {
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexSplashScreen);
		DrawBackground();
		Present();
	} 
	SplashFinshed = false;
	QueryPerformanceFrequency(&ticksPerSecondSplashScreen);
	QueryPerformanceCounter(&tickSplashScreen);
	lastTimeSplashScreen = (FLOAT)tickSplashScreen.QuadPart;
	g_hSoundThreadSplash = CreateThread(NULL, 0, Mp3player_ThreadFuncSplash, NULL, 0, &g_dwSoundThreadIdSplash);
	fadeColor = 0;
	while(!AnimateSplashScreen()) {
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexSplashScreen);
		DrawBackground();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		fade = true;
		fadeColor +=2;
		if(fadeColor > 255) { fadeColor = 255; }
		Device->SetTexture(0,TexPreview);
		DrawBackground();
		fade = false;
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		Present();
	}
	for(int i = 0; i < 90; i++) {
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		Device->SetTexture(0,TexSplashScreen);
		DrawBackground();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		fade = true;
		Device->SetTexture(0,TexPreview);
		DrawBackground();
		fade = false;
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		Present();
	} 
	m_mp3playerSplash.stop();
	fadeColor = 255;
	fadeOption = 2;
	SplashFinshed = true;
}


void SaveGameList() {
	FILE* f;
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\database.ini");
	f = fopen(fileName, "w+");
	if(!f) {
		//////////dprintf("SaveGameList Error\n");
		//////////dprintf("Error opening %s\n", fileName);
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}

	fprintf(f, "%d\n", GameDatabase.size());
	for(int i = 0; i < GameDatabase.size(); i++) {
		fprintf(f, "%s\n", GameDatabase[i].name.c_str());
		fprintf(f, "%s\n", GameDatabase[i].displayName.c_str());
		fprintf(f, "%s\n", GameDatabase[i].date.c_str());
		fprintf(f, "%s\n", GameDatabase[i].manufacturer.c_str());
		fprintf(f, "%s\n", GameDatabase[i].system.c_str());
		fprintf(f, "%s\n", GameDatabase[i].genre.c_str());
		fprintf(f, "%s\n", GameDatabase[i].parent.c_str());
	}
	fprintf(f, "%d\n", FilterCustom.size());
	for(int i = 0; i < FilterCustom.size(); i++) {
		fprintf(f, "%s\n", FilterCustom[i].c_str());
	}
	fprintf(f, "%d\n", FilterCompany.size());
	for(int i = 0; i < FilterCompany.size(); i++) {
		fprintf(f, "%s\n", FilterCompany[i].c_str());
	}
	fprintf(f, "%d\n", FilterYear.size());
	for(int i = 0; i < FilterYear.size(); i++) {
		fprintf(f, "%s\n", FilterYear[i].c_str());
	}
	fprintf(f, "%d\n", FilterGenre.size());
	for(int i = 0; i < FilterGenre.size(); i++) {
		fprintf(f, "%s\n", FilterGenre[i].c_str());
	}
	fclose(f);
}

bool LoadGameList() {
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\database.ini");
	ifstream f(fileName);
	if(!f)
		return false;
	char line[2048];
	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	int e = atoi(line);
	//////////dprintf("Number of games: %d\n", e);
	for(int i = 0; i < e; i++) {
		GameDBEntry game;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.name = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.displayName = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.date = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.manufacturer = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.system = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.genre = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.parent = line;
		GameDatabase.push_back(game);
	}

	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	e = atoi(line);
	//////////dprintf("Number of custom filters: %d\n", e);
	for(int i = 0; i < e; i++) {
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		FilterCustom.push_back(line);
	}

	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	e = atoi(line);
	//////////dprintf("Number of company filters: %d\n", e);
	for(int i = 0; i < e; i++) {
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		FilterCompany.push_back(line);
	}

	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	e = atoi(line);
	//////////dprintf("Number of year filters: %d\n", e);
	for(int i = 0; i < e; i++) {
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		FilterYear.push_back(line);
	}

	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	e = atoi(line);
	//////////dprintf("Number of genre filters: %d\n", e);
	for(int i = 0; i < e; i++) {
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		FilterGenre.push_back(line);
	}
	f.close();
	for(int i = 0; i < GameDatabase.size(); i++) {
		////////////dprintf("Adding: %s\n", GameDatabase[i].name.c_str());
		GameDatabaseTemp.push_back(GameDatabase[i]);
	}
	return true;
}

bool operator<(const GameDBEntry &l, const GameDBEntry &r) {
	std::string a = l.displayName;
	std::string b = r.displayName;
	transform(a.begin(), a.end(), a.begin(), tolower);
	transform(b.begin(), b.end(), b.begin(), tolower);
	if(a < b) return true; else return false;
}

vector <Category> gameTypelist;

void ScanDirectory(std::string PathToSearch){
	//////////dprintf("Scanning %s\n", PathToSearch.c_str());
	std::string path1 = PathToSearch;// + "*";
	std::string path2("*.zip");
	std::string path = path1 + path2;
	HANDLE find=NULL;
	WIN32_FIND_DATA wfd;
	memset(&wfd,0,sizeof(wfd));
	find=FindFirstFile(path.c_str(),&wfd);
	if (find ==INVALID_HANDLE_VALUE){ //Empty directory
		return;
	}
	else {
		do {
			if(!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
				//Not a folder		 
				std::string fileFound(wfd.cFileName);
				GameDBEntry f;
				f.name = "";
				f.displayName = "";
				f.name = fileFound;
				//////////dprintf("%s\n", f.name.c_str());
				for(int i = 0; i < f.name.size(); i++) {
					if((   (f.name.c_str())[i] == '.' 
						&& (f.name.c_str())[i+1] == 'z' 
						&& (f.name.c_str())[i+2] == 'i' 
						&& (f.name.c_str())[i+3] == 'p' 
						&& (f.name.c_str())[i+4] == '\0') 
						) {
							f.name[i] = '\0';
							break;
					}
				}

				for (i = 0; i < nBurnDrvCount; i++) {
					nBurnDrvSelect = i;
					if (_tcscmp(BurnDrvGetText(0), f.name.c_str()) == 0 &&
						(_tcscmp("neogeo", f.name.c_str()) != 0) &&
						//(_tcscmp("cuebrick", f.name.c_str()) != 0) &&
						//(_tcscmp("cuebrickj", f.name.c_str()) != 0) &&
						//(_tcscmp("dkongjr", f.name.c_str()) != 0) &&
						//(_tcscmp("bloodbro", f.name.c_str()) != 0) &&
						//(_tcscmp("tgm2", f.name.c_str()) != 0) &&
						//(_tcscmp("tgm2p", f.name.c_str()) != 0) &&
						(_tcscmp("pgm", f.name.c_str()) != 0)) {
							f.displayName = BurnDrvGetText(2);
							if(f.displayName.size() > 0) {
								f.date = BurnDrvGetText(1);
								f.manufacturer = BurnDrvGetText(5);
								f.system = BurnDrvGetText(6);
								f.genre = "";
								f.parent = "";
								if(BurnDrvGetText(7))
									f.parent = BurnDrvGetText(7);
								else
									f.parent = "NULL";

								////////////dprintf("Parent: %s\n", f.parent.c_str());
								for(int n = 0; n < gameTypelist.size(); n++) {
									////////////dprintf("%s, %s\n", gameTypelist[n].name.c_str(), gameTypelist[n].genre.c_str());
									if(_tcscmp(gameTypelist[n].name.c_str(), f.name.c_str()) == 0) {
										f.genre = gameTypelist[n].genre;
										break;
									}
								}
								GameDatabase.push_back(f);
							}
							break;
					}
				}	
			}
		} while (FindNextFile(find,&wfd) !=0);
	}
}

void GenerateDat() {
	FILE *screen = fopen("D:\\tools\\screenshot.bat", "w+");
	for (int i = 0; i < nBurnDrvCount; i++) {
		nBurnDrvSelect = i;
		string game = BurnDrvGetText(0);
		fprintf(screen, "%s%s%s%s%s\n", "copy ", game.c_str(), ".png .\\FBA\\", game.c_str(), ".png");
	}
	fclose(screen);

	FILE *list = fopen("D:\\tools\\ROM List.txt", "w+");
	for (int i = 0; i < nBurnDrvCount; i++) {
		nBurnDrvSelect = i;
		string game = BurnDrvGetText(0);
		fprintf(list, "%s\n", game.c_str());
	}
	fclose(list);

	list = fopen("D:\\tools\\Game List.txt", "w+");
	for (int i = 0; i < nBurnDrvCount; i++) {
		nBurnDrvSelect = i;
		string game = BurnDrvGetText(2);
		fprintf(list, "%s\n", game.c_str());
	}
	
	fclose(list);

	SaveDat();
}

void Scan() {
	vector <string> types;
	vector <string> catver;
	ifstream f("D:\\info\\catver.ini");
	bool save = false;
	while(!f.eof()) {
		char line[2048];
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		string t = line;
		if(t == "[Category]")
			save = true;
		if(t == "[VerAdded]")
			break;
		if(save && t.size() != 0)
			catver.push_back(t);
	}

	f.close();
	for(int i = 0; i < catver.size(); i++) {
		int e = catver[i].find("=", 0);
		if(e != -1) {
			Category n;
			n.name = catver[i].substr(0, e);
			n.genre = catver[i].substr(e + 1, catver[i].size() - e);
			string type = catver[i].substr(e + 1, catver[i].size() - e);
			if(types.size() == 0) {
				types.push_back(type);
			}
			else {
				bool found = false;
				for(int j = 0; j < types.size(); j++) {
					if(_tcscmp(types[j].c_str(), type.c_str()) == 0) {
						found = true;
						break;
					}
				}
				if(!found)
					types.push_back(type);
			}
			gameTypelist.push_back(n);
		}
	}

	GameDatabase.clear();
	char pathToSearch[260];
	if(RomPath1.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath1.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath2.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath2.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath3.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath3.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath4.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath4.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath5.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath5.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath6.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath6.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath7.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath7.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}
	if(RomPath8.size() != 0) {
		sprintf(pathToSearch,"%s%s", RomPath8.c_str(), "\\");
		ScanDirectory(pathToSearch);
	}

	if(GameDatabase.size() == 0) {
		GameDBEntry t;
		t.displayName= "No games were found";
		t.name= "";
		t.date = "";
		t.manufacturer = "";
		t.system = "";
		t.genre = "";
		t.parent = "";
		GameDatabase.push_back(t);	
	}

	FilterGenre.clear();
	FilterCustom.clear();
	FilterYear.clear();
	FilterCompany.clear();

	if(_tcscmp("", GameDatabase[0].name.c_str()) == 0) {
		FilterGenre.push_back("No genre categories were found");
		FilterYear.push_back("No year categories were found");
		FilterCompany.push_back("No company categories were found");
		FilterCustom.push_back("No games were found");
	}
	else {
		FilterCustom.push_back("CPS1");
		FilterCustom.push_back("CPS2");
		FilterCustom.push_back("NeoGeo");
		FilterCustom.push_back("CPS1 + CPS2");
		FilterCustom.push_back("CPS1 + CPS2 + NeoGeo");
		FilterCustom.push_back("Sega Genesis");
		FilterCustom.push_back("Cave");
		FilterCustom.push_back("Psykio");
		FilterCustom.push_back("Cave + Psykio");
		FilterCustom.push_back("Various");
		FilterCustom.push_back("Konami");
		FilterCustom.push_back("Sega");

		for(int i = 0; i < types.size(); i++) {
			bool found = false;
			for(int j = 0; j < GameDatabase.size(); j++) {
				if(_tcscmp(types[i].c_str(), GameDatabase[j].genre.c_str()) == 0) {
					found = true;
					break;
				}
			}
			if(found && types[i].size() != 0)
				FilterGenre.push_back(types[i]);
		}

		for(int i = 0; i < GameDatabase.size(); i++) {
			string date = GameDatabase[i].date;
			if(FilterYear.size() == 0 && date.size() != 0) {
				FilterYear.push_back(date);
			}
			else {
				bool found = false;
				for(int j = 0; j < FilterYear.size(); j++) {
					if(_tcscmp(FilterYear[j].c_str(), date.c_str()) == 0) {
						found = true;
						break;
					}
				}
				if(!found && date.size() != 0)
					FilterYear.push_back(date);
			}

			string manufacturer = GameDatabase[i].manufacturer;
			if(FilterCompany.size() == 0 && manufacturer.size() != 0) {
				FilterCompany.push_back(manufacturer);
			}
			else {
				bool found = false;
				for(int j = 0; j < FilterCompany.size(); j++) {
					if(_tcscmp(FilterCompany[j].c_str(), manufacturer.c_str()) == 0) {
						found = true;
						break;
					}
				}
				if(!found && manufacturer.size() != 0)
					FilterCompany.push_back(manufacturer);
			}
		}

		if(FilterGenre.size() == 0)
			FilterGenre.push_back("No genre categories were found");
		if(FilterYear.size() == 0)
			FilterYear.push_back("No year categories were found");
		if(FilterCompany.size() == 0)
			FilterCompany.push_back("No company categories were found");

		sort(FilterCompany.begin(), FilterCompany.end());
		sort(FilterYear.begin(), FilterYear.end());
		sort(FilterGenre.begin(), FilterGenre.end());
		sort(GameDatabase.begin(), GameDatabase.end());
	}

	GameDatabaseTemp.clear();
	for(int i = 0; i < GameDatabase.size(); i++) {
		GameDatabaseTemp.push_back(GameDatabase[i]);
	}

	SaveGameList();
	GameSelected = 0;
}

void AddToFavorites() {
	GameDBEntry e;
	e.name = GameDatabase[GameSelected].name;
	e.displayName =  GameDatabase[GameSelected].displayName;
	e.date =  GameDatabase[GameSelected].date;
	e.manufacturer =  GameDatabase[GameSelected].manufacturer;
	e.system =  GameDatabase[GameSelected].system;
	e.genre =  GameDatabase[GameSelected].genre;
	e.parent =  GameDatabase[GameSelected].parent;

	if(FavoritesDatabase.size() == 1) {
		if(FavoritesDatabase[0].displayName == "No Favorites Found")
			FavoritesDatabase.clear();
	}
	FavoritesDatabase.push_back(e);
	sort(FavoritesDatabase.begin(), FavoritesDatabase.end());
}

void UpdatePreview(string game, string parent) {
	if(!PreviewSwitch) {
		CurrentArtwork = 1;
		//GameInfoDetailSelected = (GameInfoDetailNumLines / 2);
		//GameInfoDetail.clear();
		char fileName[260];
		//sprintf(fileName,"%s%s%s", "D:\\info\\gui\\", game.c_str(), ".ini");
		//ifstream f(fileName);
		//if(f) {
		//	while(!f.eof()) {
		//		char line[2048];
		//		//for(int i = 0; i < 2048; i++) line[i] = '\0';
		//		f.getline(line, 2048);
		//		string t = line;
		//		GameInfoDetail.push_back(t);
		//	}
		//	f.close();
		//}

		if(MovieEnabled) {
			stopMovie();
			sprintf(fileName,"%s%s%s%s", VideoPath.c_str(), "\\", game.c_str(), ".xmv");
			FILE* f = fopen(fileName, "r");
			if(f) {
				fclose(f);
				initMovie(fileName);
			}
			if(videoRender) {
				dprintf("Pausing Music\n");
				m_mp3player.pause(TRUE);
			}
			else {
				m_mp3player.pause(FALSE);
			}
		}

		if(TexPreview) {
			TexPreview->Release();
			TexPreview = NULL;
		}
		sprintf(fileName,"%s%s%s%s", ArtworkPath1.c_str(), "\\", game.c_str(), ".png");
		//f = fopen(fileName, "r");
		//if(f) {
			//fclose(f);
			D3DXIMAGE_INFO ImageStats;
			D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
				D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
				D3DX_DEFAULT,0,&ImageStats,NULL,&TexPreview);
			if(TexPreview) {
				SourceWidth = ImageStats.Width;
				SourceHeight = ImageStats.Height;
				////////////dprintf("SourceWidth: %d\n", SourceWidth);
				////////////dprintf("SourceHeight: %d\n", SourceHeight);
			}
		//}
	}
	else {
		string e = ArtworkPath1;
		PreviewSwitch = false;
		if(CurrentArtwork == 1) e = ArtworkPath1;
		if(CurrentArtwork == 2) e = ArtworkPath2;
		if(CurrentArtwork == 3) e = ArtworkPath3;
		if(CurrentArtwork == 4) e = ArtworkPath4;
		if(CurrentArtwork == 5) e = ArtworkPath5;
		if(CurrentArtwork == 6) e = ArtworkPath6;
		if(CurrentArtwork == 7) e = ArtworkPath7;
		if(CurrentArtwork == 8) e = ArtworkPath8;
		if(TexPreview) {
			TexPreview->Release();
			TexPreview = NULL;
		}
		char fileName[260];
		sprintf(fileName,"%s%s%s%s", e.c_str(), "\\", game.c_str(), ".png");
		D3DXIMAGE_INFO ImageStats;
		D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
			D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
			D3DX_DEFAULT,0,&ImageStats,NULL,&TexPreview);
		if(TexPreview) {
			SourceWidth = ImageStats.Width;
			SourceHeight = ImageStats.Height;
			//////////dprintf("SourceWidth: %d\n", SourceWidth);
			//////////dprintf("SourceHeight: %d\n", SourceHeight);
		}
	}
}

void SetRenderStates() {
	Device->SetRenderState(D3DRS_LIGHTING,0);
	Device->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
	Device->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
	Device->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
	Device->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_MODULATE );
	Device->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
	Device->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
	Device->SetTextureStageState( 1, D3DTSS_COLOROP,   D3DTOP_DISABLE );
	Device->SetTextureStageState( 1, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );
	Device->SetTextureStageState( 0, D3DTSS_ADDRESSU,  D3DTADDRESS_CLAMP );
	Device->SetTextureStageState( 0, D3DTSS_ADDRESSV,  D3DTADDRESS_CLAMP );
	Device->SetRenderState( D3DRS_ZENABLE,      FALSE );
	Device->SetRenderState( D3DRS_FOGENABLE,    FALSE );
	Device->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_NONE );
	Device->SetRenderState( D3DRS_FILLMODE,     D3DFILL_SOLID );
	Device->SetRenderState( D3DRS_CULLMODE,     D3DCULL_CCW );
	Device->SetRenderState( D3DRS_SRCBLEND,  D3DBLEND_SRCALPHA );
	Device->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
	Device->SetVertexShader( D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1);
}

void DisplayFPS() {
	WCHAR fpsDisplay[80]={0};
	wsprintfW(fpsDisplay, L"%1f", fps);
	FontSetColour(0xffff00);
	FontText(fpsDisplay, DebugX, DebugY, 640);
}

void Debug() {
	//return;
	//DisplayFreeMemory();
	if(Emulation) DisplayFPS();
}

extern "C" int dprintf(char *format, ...) {
	return 0;
	char *name=NULL;
	va_list val=NULL;
	name="D:\\GeneralError.txt";

#ifdef CAVE 
	name="D:\\CaveError.txt";
#endif

#ifdef NEOGEOCPS2 
	name="D:\\NeoGeoCPS2Error.txt";
#endif

#ifdef PSYKIO 
	name="D:\\PsykioError.txt";
#endif

#ifdef TOAPLAN 
	name="D:\\ToaplanError.txt";
#endif

	if (DebugFile==NULL) DebugFile=fopen(name,"wt");
	if (DebugFile==NULL) return 1;
	va_start(val,format);
	vfprintf(DebugFile,format,val);
	fflush(DebugFile);
	va_end(val);
	return 0;
}

void DisplayInstructions(char* text) {
	FontSetColour(0xffff00);
	FontGUI(ConvertCharStringToWCHAR(text), 320, 240, 640);
	FontGUI(ConvertCharStringToWCHAR("Press \"B\" to exit"), 320, 240 + vSpace, 640);
}

void ZeroTexture() {
	D3DSURFACE_DESC desc;
	TexScreen->GetLevelDesc( 0, &desc );
	DWORD dwTexWidth  = desc.Width;
	DWORD dwTexHeight = desc.Height;
	D3DLOCKED_RECT lock;
	TexScreen->LockRect( 0, &lock, 0, 0L );
	VOID* pBits = lock.pBits;
	for( DWORD y = 0; y < dwTexHeight; y++ ) {
		for( DWORD x = 0; x < dwTexWidth; x++ ) {
			((unsigned short*)pBits)[y*dwTexWidth+x] = 0;//0x00FF;
		}
	}
	TexScreen->UnlockRect( 0 );
}

void SetupDefaultPaths() {
	RomPath1 = "D:\\roms";
	RomPath2 = "";
	RomPath3 = "";
	RomPath4 = "";
	RomPath5 = "";
	RomPath6 = "";
	RomPath7 = "";
	RomPath8 = "";
	ArtworkPath1="E:\\FinalBurnLegends\\artwork\\Shots 1";
	ArtworkPath2="E:\\FinalBurnLegends\\artwork\\Shots 2";
	ArtworkPath3="E:\\FinalBurnLegends\\artwork\\Shots 3";
	ArtworkPath4="E:\\FinalBurnLegends\\artwork\\Shots 4";
	ArtworkPath5="E:\\FinalBurnLegends\\artwork\\Shots 5"; 
	ArtworkPath6="E:\\FinalBurnLegends\\artwork\\Shots 6"; 
	ArtworkPath7="E:\\FinalBurnLegends\\artwork\\Shots 7"; 
	ArtworkPath8="E:\\FinalBurnLegends\\artwork\\Shots 8"; 
	NVRAMPath="E:\\FinalBurnLegends\\nvram"; 
	IniPath="E:\\FinalBurnLegends\\ini"; 
	SaveStatePath="E:\\FinalBurnLegends\\savestates"; 
	ConfigPath="E:\\FinalBurnLegends\\config";
	HiScorePath="E:\\FinalBurnLegends\\hiscores";
	mkdir("E:\\FinalBurnLegends");
	mkdir("E:\\FinalBurnLegends\\artwork");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 1");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 2");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 3");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 4");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 5");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 6");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 7");
	mkdir("E:\\FinalBurnLegends\\artwork\\Shots 8");
	mkdir("E:\\FinalBurnLegends\\nvram");
	mkdir("E:\\FinalBurnLegends\\ini");
	mkdir("E:\\FinalBurnLegends\\ini\\controller");
	mkdir("E:\\FinalBurnLegends\\ini\\emulation");
	mkdir("E:\\FinalBurnLegends\\savestates");
	mkdir("E:\\FinalBurnLegends\\config");
	mkdir("E:\\FinalBurnLegends\\config\\games");
	mkdir("E:\\FinalBurnLegends\\config\\dip");
	mkdir("E:\\FinalBurnLegends\\hiscores");
}

void SetupPath() {
	FILE* f;
	f = fopen("D:\\Path.ini" , "r");
	if(!f) {
		SetupDefaultPaths();
		return;
	}
	UsePathINI = GetFileInteger(f);

	if(UsePathINI == 1) {
		RomPath1 = GetFileString(f);
		RomPath2 = GetFileString(f);
		RomPath3 = GetFileString(f);
		RomPath4 = GetFileString(f);
		RomPath5 = GetFileString(f);
		RomPath6 = GetFileString(f);
		RomPath7 = GetFileString(f);
		RomPath8 = GetFileString(f);
		ArtworkPath1 = GetFileString(f);
		ArtworkPath2 = GetFileString(f);
		ArtworkPath3 = GetFileString(f);
		ArtworkPath4 = GetFileString(f);
		ArtworkPath5 = GetFileString(f);
		ArtworkPath6 = GetFileString(f);
		ArtworkPath7 = GetFileString(f);
		ArtworkPath8 = GetFileString(f);
		NVRAMPath = GetFileString(f);
		IniPath = GetFileString(f);
		SaveStatePath = GetFileString(f);
		ConfigPath = GetFileString(f);
		HiScorePath = GetFileString(f);
		VideoPath = GetFileString(f);
		char fileName[260];
		sprintf(fileName,"%s%s", IniPath.c_str(), "\\emulation");
		mkdir(fileName);
		sprintf(fileName,"%s%s", IniPath.c_str(), "\\controller");
		mkdir(fileName);
		sprintf(fileName,"%s%s", ConfigPath.c_str(), "\\games");
		mkdir(fileName);
		sprintf(fileName,"%s%s", ConfigPath.c_str(), "\\dip");
		mkdir(fileName);
		fclose(f);
	}
	else {
		SetupDefaultPaths();
		fclose(f);
	}
	//////////dprintf("Current Paths\n");
	//////////dprintf("RomPath1: %s\n", RomPath1.c_str());
	//////////dprintf("RomPath2: %s\n", RomPath2.c_str());
	//////////dprintf("RomPath3: %s\n", RomPath3.c_str());
	//////////dprintf("RomPath4: %s\n", RomPath4.c_str());
	//////////dprintf("RomPath5: %s\n", RomPath5.c_str());
	//////////dprintf("RomPath6: %s\n", RomPath6.c_str());
	//////////dprintf("RomPath7: %s\n", RomPath7.c_str());
	//////////dprintf("RomPath8: %s\n", RomPath8.c_str());
	//////////dprintf("ArtworkPath1: %s\n", ArtworkPath1.c_str());
	//////////dprintf("ArtworkPath2: %s\n", ArtworkPath2.c_str());
	//////////dprintf("ArtworkPath3: %s\n", ArtworkPath3.c_str());
	//////////dprintf("ArtworkPath4: %s\n", ArtworkPath4.c_str());
	//////////dprintf("ArtworkPath5: %s\n", ArtworkPath5.c_str());
	//////////dprintf("ArtworkPath6: %s\n", ArtworkPath6.c_str());
	//////////dprintf("ArtworkPath7: %s\n", ArtworkPath7.c_str());
	//////////dprintf("ArtworkPath8: %s\n", ArtworkPath8.c_str());
	//////////dprintf("NVRAMPath: %s\n", NVRAMPath.c_str());
	//////////dprintf("IniPath: %s\n", IniPath.c_str());
	//////////dprintf("SaveStatePath: %s\n", SaveStatePath.c_str());
	//////////dprintf("ConfigPath: %s\n", ConfigPath.c_str());
	//////////dprintf("HiScorePath: %s\n", HiScorePath.c_str());
}

HRESULT Mount(const char* szDrive, char* szDevice)
{
	char szSourceDevice[256];
	char szDestinationDrive[16];

	sprintf(szSourceDevice,"\\Device\\%s",szDevice);
	sprintf(szDestinationDrive,"\\??\\%s",szDrive);

	STRING DeviceName =
	{
		strlen(szSourceDevice),
		strlen(szSourceDevice) + 1,
		szSourceDevice
	};

	STRING LinkName =
	{
		strlen(szDestinationDrive),
		strlen(szDestinationDrive) + 1,
		szDestinationDrive
	};

	IoCreateSymbolicLink(&LinkName, &DeviceName);

	return S_OK;
}

HRESULT Unmount(const char* szDrive)
{
	char szDestinationDrive[16];
	sprintf(szDestinationDrive,"\\??\\%s",szDrive);

	STRING LinkName =
	{
		strlen(szDestinationDrive),
		strlen(szDestinationDrive) + 1,
		szDestinationDrive
	};

	IoDeleteSymbolicLink(&LinkName);

	return S_OK;
}
