#include "GlobalExtern.h"

string ImageMessage = "Not enough free memory";
int ImageCategorySelected = 0;
string gameName;
int RomBrowser = 0;

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

void ClearImageList() {
	ImageDatabase.clear();
}

void SearchDirectoryImage(std::string pathToSearch) {
	ImageDatabase.clear();
	//dprintf("Path: %s\n", pathToSearch.c_str());
	ImageGameSelected = 0;
	std::string path1 = pathToSearch;// + "*";
	std::string path2("*");
	std::string path = path1 + path2;
	HANDLE find=NULL;
	WIN32_FIND_DATA wfd;
	//dprintf("Path Q: %s\n", pathToSearch.c_str());
	memset(&wfd,0,sizeof(wfd));
	find=FindFirstFile(path.c_str(),&wfd);

	if (find ==INVALID_HANDLE_VALUE){ //Empty directory
		ImageDBEntry t, t2;
		t.name = "No Image files were found";
		t.path = "";
		t.isADirectory = false;
		t.topLevel = false;
		t.isARoot = false;
		ImageDatabase.push_back(t);
		return;
	}

	do {
		if(!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
			//Not a folder		 
			std::string fileFound(wfd.cFileName);

			int r1 = fileFound.find(".png", 0);
			int r2 = fileFound.find(".PNG", 0);
			int r3 = fileFound.find(".jpg", 0);
			int r4 = fileFound.find(".JPG", 0);
			int r5 = fileFound.find(".dds", 0);
			int r6 = fileFound.find(".DDS", 0);
			int r7 = fileFound.find(".tga", 0);
			int r8 = fileFound.find(".TGA", 0);

			if( r1 != string::npos || r2 != string::npos ||
				r3 != string::npos || r4 != string::npos ||
				r5 != string::npos || r6 != string::npos |
				r7 != string::npos || r8 != string::npos) {
					ImageDBEntry f;
					f.name = fileFound;
					f.path = pathToSearch + fileFound;
					f.isADirectory = false;
					ImageDatabase.push_back(f);	
				}
		}
		else {
			std::string folderName(wfd.cFileName);
			folderName = "<" + folderName + ">"; 

			ImageDBEntry d;
			d.name = folderName;
			std::string folderNameNoBrackets(wfd.cFileName);
			d.path = pathToSearch +  folderNameNoBrackets + "\\";
			d.isAGame = false;
			d.isARoot = false;
			d.isADirectory = true;
			d.topLevel = false;
			//dprintf("Directory Name: %s\n", (char*)d.name.c_str());
			//dprintf("Directory Path: %s\n", (char*)d.path.c_str());
			ImageDatabase.push_back(d);
		}
	} while (FindNextFile(find,&wfd) !=0);
	sort(ImageDatabase.begin(), ImageDatabase.end());
}

void BuildImageList() {
	ImageDatabase.clear();
	ImageDirectories.clear();
	SearchDirectoryImage("D:\\Images\\");
	ImageDirectories.push_back("D:\\Images\\");

}
void FreeImage() {
	//if(TexPreviewBorder) {TexPreviewBorder->Release();TexPreviewBorder = NULL;}
	//if(TexAnimatedLogo) {TexAnimatedLogo->Release();TexAnimatedLogo = NULL;}
	//if(TexVideoBorder) {TexVideoBorder->Release();TexVideoBorder = NULL;}
	//if(TexROMBorder) {TexROMBorder->Release();TexROMBorder = NULL;}
	//if(TexSelectedBorder) {TexSelectedBorder->Release();TexSelectedBorder = NULL;}
	if(TexOption) {TexOption->Release();TexOption = NULL;}
	if(TexROMBrowser) {TexROMBrowser->Release();TexROMBrowser = NULL;}
	//if(TexAnimatedLogoMainMenu) {TexAnimatedLogoMainMenu->Release();TexAnimatedLogoMainMenu = NULL;}
	//if(TexMainMenuOverlay) {TexMainMenuOverlay->Release();TexMainMenuOverlay = NULL;}
	//if(TexMainMenu) {TexMainMenu->Release();TexMainMenu = NULL;}
}

void InitImage() {
	BuildImageList();
	FreeImage();
}

void CloseImageMenu() {
	char fileName[260];

	if(TexImage) {TexImage->Release();TexImage = NULL;}
	
	/*sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\logo.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexAnimatedLogo);

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\selectedborder.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexSelectedBorder);*/

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\option.png");
		D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
			D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
			D3DX_DEFAULT,0,NULL,NULL,&TexOption);

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\rombrowser.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexROMBrowser);

	/*sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\logomainmenu.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexAnimatedLogoMainMenu);*/

	/*sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\previewborder.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexPreviewBorder);

	

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\videoborder.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexVideoBorder);

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\romborder.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexROMBorder);

	

	

	/*

	sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\overlay.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexMainMenuOverlay);*/

	/*sprintf(fileName,"%s%s%s", "D:\\skins\\", SkinPath.c_str(), "\\mainmenu.png");
	D3DXCreateTextureFromFileEx(Device, fileName, D3DX_DEFAULT,
		D3DX_DEFAULT,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,
		D3DX_DEFAULT,0,NULL,NULL,&TexMainMenu);*/
}

void ImageListDeleteInput() {
	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
		CancelSound();
		ImageList = 1;
		ImageSelected = 0;
		ImageListDelete = 0;
		return;          
	}
	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_Y) {
		CancelSound();
		ImageList = 1;
		ImageSelected = 0;
		ImageListDelete = 0;
		//if(DisableMenuSounds == 0) playEffect(1);

		//std::string a = GARBAGE_PATH;//
		//std::string newName = a + TGADatabase[TGAGameSelected].name.c_str();
		//newName += ".png";
		//int r = MoveFileEx(TGADatabase[TGAGameSelected].path.c_str(),  newName.c_str(), MOVEFILE_COPY_ALLOWED);
		//TGADatabaseDelete = 0;
		//screenGeneralOptionsTGA = 1;
		//buildTGAList();
		return;
	}
}

bool LoadEmulationImage(char* image) {

	if(TexImage) {TexImage->Release();TexImage = NULL;}

	DWORD dwTexWidth  = 0;//desc.Width;
	DWORD dwTexHeight = 0;//desc.Height;
	D3DXIMAGE_INFO           pSrcInfo;
	//dprintf("Image: %s\n", image);
	if(FAILED(D3DXCreateTextureFromFileEx(Device, 
		image, 
		32, //Width:D3DX_DEFAULT = Take from file 
		32, //Height:D3DX_DEFAULT = Take from file
		1,            //MipLevels
		0,            //Usage, Is this to be used as a Render Target? 0 == No
		D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
		D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
		D3DX_DEFAULT, D3DX_DEFAULT,
		0,            //Disable ColourKey
		&pSrcInfo,         //SourceInfo, returns extra info if we want it (we don't)
		NULL,         //Palette:We're not using one
		&TexImage ))) {
			ImageMessage = "No image found";
			return false;
		}
		dwTexWidth  = pSrcInfo.Width;
		dwTexHeight = pSrcInfo.Height;
		if(TexImage) {TexImage->Release();TexImage = NULL;}

		if(FAILED(D3DXCreateTextureFromFileEx(Device, 
			image, 
			D3DX_DEFAULT, 
			D3DX_DEFAULT,
			1,            //MipLevels
			0,            //Usage, Is this to be used as a Render Target? 0 == No
			D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
			D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
			D3DX_DEFAULT, D3DX_DEFAULT,
			0,            //Disable ColourKey
			NULL,         //SourceInfo, returns extra info if we want it (we don't)
			NULL,         //Palette:We're not using one
			&TexImage ))) {
				if(TexImage) {TexImage->Release();TexImage = NULL;}
				if(dwTexWidth > dwTexHeight) {
					//dwTexWidth  = 1024;
					//dwTexHeight = 768;
					if(FAILED(D3DXCreateTextureFromFileEx(Device, 
						image, 
						1024, //Width:D3DX_DEFAULT = Take from file 
						768, //Height:D3DX_DEFAULT = Take from file
						1,            //MipLevels
						0,            //Usage, Is this to be used as a Render Target? 0 == No
						D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
						D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
						D3DX_DEFAULT, D3DX_DEFAULT,
						0,            //Disable ColourKey
						NULL,         //SourceInfo, returns extra info if we want it (we don't)
						NULL,         //Palette:We're not using one
						&TexImage ))) {
							//dwTexWidth  = 800;
							//dwTexHeight = 600;
							if(TexImage) {TexImage->Release();TexImage = NULL;}
							if(FAILED(D3DXCreateTextureFromFileEx(Device, 
								image, 
								800, //Width:D3DX_DEFAULT = Take from file 
								600, //Height:D3DX_DEFAULT = Take from file
								1,            //MipLevels
								0,            //Usage, Is this to be used as a Render Target? 0 == No
								D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
								D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
								D3DX_DEFAULT, D3DX_DEFAULT,
								0,            //Disable ColourKey
								NULL,         //SourceInfo, returns extra info if we want it (we don't)
								NULL,         //Palette:We're not using one
								&TexImage ))) {
									//dwTexWidth  = 640;
									//dwTexHeight = 480;
									if(TexImage) {TexImage->Release();TexImage = NULL;}
									if(FAILED(D3DXCreateTextureFromFileEx(Device, 
										image, 
										640, //Width:D3DX_DEFAULT = Take from file 
										480, //Height:D3DX_DEFAULT = Take from file
										1,            //MipLevels
										0,            //Usage, Is this to be used as a Render Target? 0 == No
										D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
										D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
										D3DX_DEFAULT, D3DX_DEFAULT,
										0,            //Disable ColourKey
										NULL,         //SourceInfo, returns extra info if we want it (we don't)
										NULL,         //Palette:We're not using one
										&TexImage ))) {
											dwTexWidth  = 320;
											dwTexHeight = 240;
											if(TexImage) {TexImage->Release();TexImage = NULL;}
											if(FAILED(D3DXCreateTextureFromFileEx(Device, 
												image, 
												320, //Width:D3DX_DEFAULT = Take from file 
												240, //Height:D3DX_DEFAULT = Take from file
												1,            //MipLevels
												0,            //Usage, Is this to be used as a Render Target? 0 == No
												D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
												D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
												D3DX_DEFAULT, D3DX_DEFAULT,
												0,            //Disable ColourKey
												NULL,         //SourceInfo, returns extra info if we want it (we don't)
												NULL,         //Palette:We're not using one
												&TexImage ))) {
													if(TexImage) {TexImage->Release();TexImage = NULL;}
													//ImageMessage = "Not enough free memory";
													return false;
												}
										}
								}
						}

				}
				else {

					//dwTexWidth  = 768;
					//dwTexHeight = 1024;
					if(FAILED(D3DXCreateTextureFromFileEx(Device, 
						image, 
						768, //Width:D3DX_DEFAULT = Take from file 
						1024, //Height:D3DX_DEFAULT = Take from file
						1,            //MipLevels
						0,            //Usage, Is this to be used as a Render Target? 0 == No
						D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
						D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
						D3DX_DEFAULT, D3DX_DEFAULT,
						0,            //Disable ColourKey
						NULL,         //SourceInfo, returns extra info if we want it (we don't)
						NULL,         //Palette:We're not using one
						&TexImage ))) {
							//dwTexWidth  = 600;
							//dwTexHeight = 800;
							if(TexImage) {TexImage->Release();TexImage = NULL;}
							if(FAILED(D3DXCreateTextureFromFileEx(Device, 
								image, 
								600, //Width:D3DX_DEFAULT = Take from file 
								800, //Height:D3DX_DEFAULT = Take from file
								1,            //MipLevels
								0,            //Usage, Is this to be used as a Render Target? 0 == No
								D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
								D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
								D3DX_DEFAULT, D3DX_DEFAULT,
								0,            //Disable ColourKey
								NULL,         //SourceInfo, returns extra info if we want it (we don't)
								NULL,         //Palette:We're not using one
								&TexImage ))) {
									//dwTexWidth  = 480;
									//dwTexHeight = 640;
									if(TexImage) {TexImage->Release();TexImage = NULL;}
									if(FAILED(D3DXCreateTextureFromFileEx(Device, 
										image, 
										480, //Width:D3DX_DEFAULT = Take from file 
										640, //Height:D3DX_DEFAULT = Take from file
										1,            //MipLevels
										0,            //Usage, Is this to be used as a Render Target? 0 == No
										D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
										D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
										D3DX_DEFAULT, D3DX_DEFAULT,
										0,            //Disable ColourKey
										NULL,         //SourceInfo, returns extra info if we want it (we don't)
										NULL,         //Palette:We're not using one
										&TexImage ))) {
											//dwTexWidth  = 240;
											//dwTexHeight = 320;
											if(TexImage) {TexImage->Release();TexImage = NULL;}
											if(FAILED(D3DXCreateTextureFromFileEx(Device, 
												image, 
												240, //Width:D3DX_DEFAULT = Take from file 
												320, //Height:D3DX_DEFAULT = Take from file
												1,            //MipLevels
												0,            //Usage, Is this to be used as a Render Target? 0 == No
												D3DFMT_UNKNOWN, //32-bit with Alpha, everything should support this
												D3DPOOL_MANAGED,//Pool, let D3D Manage our memory
												D3DX_DEFAULT, D3DX_DEFAULT,
												0,            //Disable ColourKey
												NULL,         //SourceInfo, returns extra info if we want it (we don't)
												NULL,         //Palette:We're not using one
												&TexImage ))) {
													if(TexImage) {TexImage->Release();TexImage = NULL;}
													//ImageMessage = "Not enough free memory";
													return false;
												}
										}
								}
						}
				}
			}

			if(TexImage) {
				if(dwTexHeight > dwTexWidth) {
					zTopBI = 9.44;
					zLeftBI = -12.8;
					zRightBI = -12.8 + (((float)dwTexWidth/ (float)640 ) * (12.8f * 2.0f));
					zBottomBI = 9.44 - (((float)dwTexHeight / (float)480) * (9.44f * 2.0f));
					if(zBottomBI < -7.44) {
						while(zBottomBI < -7.44) {
							float w2 = zRightBI - zLeftBI;
							float h2 = zTopBI - zBottomBI;
							zRightBI-=w2 * 0.01f; zBottomBI+=h2 * 0.01f; 
						}
					}
					else {
						while(zBottomBI >= -7.44) {
							float w2 = zRightBI - zLeftBI;
							float h2 = zTopBI - zBottomBI;
							zRightBI+=w2 * 0.01f; zBottomBI-=h2 * 0.01f; 
						}
					}
				}
				else {
					zTopBI = 9.44;
					zLeftBI = -12.8;
					zRightBI = -12.8 + (((float)dwTexWidth/ (float)640 ) * (12.8f * 2.0f));
					zBottomBI = 9.44 - (((float)dwTexHeight / (float)480) * (9.44f * 2.0f));
					if(zRightBI > 10.88) {
						while(zRightBI > 10.88) {
							float w2 = zRightBI - zLeftBI;
							float h2 = zTopBI - zBottomBI;
							zRightBI-=w2 * 0.01f; zBottomBI+=h2 * 0.01f; 
						}
					}
					else {
						while(zRightBI <= 10.88) {
							float w2 = zRightBI - zLeftBI;
							float h2 = zTopBI - zBottomBI;
							zRightBI+=w2 * 0.01f; zBottomBI-=h2 * 0.01f; 
						}
					}
				}

				float w = zRightBI - zLeftBI;
				float h = zTopBI - zBottomBI;
				zTopBI = 0 +  (h / 2);
				zBottomBI = zTopBI - h;
				zLeftBI =	0 - ((w) / 2);
				zRightBI = zLeftBI + w;
			}

			return true;
}
void ImageListInput() {
	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) {
		if(slowImage >= 1)  { 
			slowImage = 0;
		}
		if(leftAnalog == 255)
			slowImage = scrollSpeed;
		else
			slowImage += ((float)leftAnalog/255.0f);
		ImageGameSelected-=((int)slowImage); if(ImageGameSelected < 0) ImageGameSelected = 0;
		return;
	}

	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) {
		if(slowImage >= 1) { 
			slowImage = 0; 
		} 
		if(rightAnalog == 255)
			slowImage = scrollSpeed;
		else
			slowImage += ((float)rightAnalog/255.0f);
		ImageGameSelected+=((int)slowImage); if(ImageGameSelected >= ImageDatabase.size()) ImageGameSelected = ImageDatabase.size() - 1;
		return;
	}

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_UP)  {  
		if(ImageGameSelected != 0) ClickSound();
		ImageGameSelected--; if(ImageGameSelected < 0) ImageGameSelected = 0;
		return;
	}  

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_DOWN)  {  
		if(ImageGameSelected != (ImageDatabase.size() - 1)) ClickSound();	
		ImageGameSelected++; if(ImageGameSelected >= ImageDatabase.size()) ImageGameSelected = ImageDatabase.size() - 1;
		return;
	}  

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
		if(ImageDirectories.size() == 1) {
			CancelSound();
			DrawImageMenu = 0;
			ImageList = 0;
			ImageSelected = 0;
			ImageListDelete = 0;
			ClearImageList();
			return;  
		}
		else {
			CancelSound();
			ImageDirectories.erase(ImageDirectories.begin() + (ImageDirectories.size() - 1), ImageDirectories.begin() + (ImageDirectories.size() - 1) + 1);
			string q = ImageDirectories[ImageDirectories.size() - 1];
			SearchDirectoryImage(q);
		}
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
		ConfirmSound();
		dprintf("ImageGameSelected: %d\n", ImageGameSelected);
		dprintf("ImageDatabase[ImageGameSelected].name: %s\n", (char*)ImageDatabase[ImageGameSelected].name.c_str());
		dprintf("ImageDatabase[ImageGameSelected].path: %s\n", (char*)ImageDatabase[ImageGameSelected].path.c_str());
		dprintf("ImageDatabase[ImageGameSelected].Directory: %d\n", (int)ImageDatabase[ImageGameSelected].isADirectory);
		if(ImageDatabase[ImageGameSelected].isADirectory) {
			ImageDirectories.push_back(ImageDatabase[ImageGameSelected].path);
			SearchDirectoryImage(ImageDatabase[ImageGameSelected].path);
			return;
		}
		FontSetColour(0xffff00);
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		SetupMatrices();
		MakeVertexListMenu();
		FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
		Present();
		ImageList = 0;
		ImageSelected = 1;
		ImageListDelete = 0;
		LoadEmulationImage((char*)ImageDatabase[ImageGameSelected].path.c_str());	
		return;
	} 

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_BLACK) {
		ConfirmSound();
		ImageList = 0;
		ImageSelected = 0;
		ImageListDelete = 1;
		return;
	} 
}

void ImageSelectedInput() {
	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
		CancelSound();
		if(TexImage) {
			TexImage->Release();
			TexImage = NULL;
		}
		ImageList = 1;
		ImageSelected = 0;
		ImageListDelete = 0;
	} 

	if (g_Gamepads[DefaultController].fY1 > 0) {zTopBI+=imageMovementSpeed;  zBottomBI+=imageMovementSpeed; }// Up
	if (g_Gamepads[DefaultController].fY1 < 0) {zTopBI-=imageMovementSpeed;  zBottomBI-=imageMovementSpeed; } // Down
	if (g_Gamepads[DefaultController].fX1 < 0) {zLeftBI-=imageMovementSpeed; zRightBI-=imageMovementSpeed; } // Left
	if (g_Gamepads[DefaultController].fX1 > 0) {zLeftBI+=imageMovementSpeed; zRightBI+=imageMovementSpeed; }// Right

	if (g_Gamepads[DefaultController].fY2 < 0) { 
		float w = zRightBI - zLeftBI;
		float h = zTopBI - zBottomBI;
		zRightBI-= w * imageScaleSpeed; zBottomBI+= h * imageScaleSpeed; 
	}// Left

	if (g_Gamepads[DefaultController].fY2 > 0) {
		float w = zRightBI - zLeftBI;
		float h = zTopBI - zBottomBI;
		zRightBI+=w * imageScaleSpeed; zBottomBI-=h * imageScaleSpeed; 
	}// Right

	if(RomBrowser == 1) {
		if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) {
			FontSetColour(0xffff00);
			Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
			SetupMatrices();
			MakeVertexListMenu();
		    FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
			Present();
			ImageCategorySelected++;
			if(ImageCategorySelected > 5)
				ImageCategorySelected = 0;

			for(int i = 0; i < 6; i++) {
				char fileName[260];
				if(ImageCategorySelected == 0) sprintf(fileName,"%s%s%s", "D:\\Images\\cpanel\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 1) sprintf(fileName,"%s%s%s", "D:\\Images\\marquee\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 2) sprintf(fileName,"%s%s%s", "D:\\Images\\cabinet\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 3) sprintf(fileName,"%s%s%s", "D:\\Images\\flyers\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 4) sprintf(fileName,"%s%s%s", "D:\\Images\\snap\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 5) sprintf(fileName,"%s%s%s", "D:\\Images\\title\\", (char*)gameName.c_str(), ".png");
				
				if(!LoadEmulationImage(fileName)) {
					if(ImageCategorySelected == 5)
						ImageCategorySelected = 0;
					else
						ImageCategorySelected++;
				}
			}
		}

		if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_DPAD_LEFT) {
			FontSetColour(0xffff00);
			Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
			SetupMatrices();
			MakeVertexListMenu();
		    FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
			Present();
			ImageCategorySelected--;
			if(ImageCategorySelected < 0)
				ImageCategorySelected = 5;

			for(int i = 0; i < 6; i++) {
				char fileName[260];
				if(ImageCategorySelected == 0) sprintf(fileName,"%s%s%s", "D:\\Images\\cpanel\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 1) sprintf(fileName,"%s%s%s", "D:\\Images\\marquee\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 2) sprintf(fileName,"%s%s%s", "D:\\Images\\cabinet\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 3) sprintf(fileName,"%s%s%s", "D:\\Images\\flyers\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 4) sprintf(fileName,"%s%s%s", "D:\\Images\\snap\\", (char*)gameName.c_str(), ".png");
				if(ImageCategorySelected == 5) sprintf(fileName,"%s%s%s", "D:\\Images\\title\\", (char*)gameName.c_str(), ".png");
				
				if(!LoadEmulationImage(fileName)) {
					if(ImageCategorySelected == 0)
						ImageCategorySelected = 5;
					else
						ImageCategorySelected--;
				}
			}
		}
	}
}

void MakeVertexListImage() {
	struct CustomVertex *vert=NULL,*pv=NULL;
	
	vert=VertexListImage;
	pv=vert;
	pv->z=10;
	pv->x= zLeftBI; 
	pv->y=zTopBI;// + topY;
	pv->colour=0xffffffff; 
	pv++;

	*pv=vert[0]; 
	pv->x= zRightBI;// + rightX; 
	pv->y=  zTopBI;//+ topY; 
	pv++;

	*pv=vert[0];
	pv->x=zLeftBI; 
	pv->y=zBottomBI;// + bottomY; 
	pv++;

	*pv=vert[0]; 
	pv->x=  zRightBI;// + rightX; 
	pv->y=zBottomBI;// + bottomY; 
	pv++;


	float right=0.0f,bottom=0.0f;
	// Find where the screen images ends on the texture
	right = 1;//(float)EmuWidth /(float)TexWidth;
	bottom= 1;//(float)EmuHeight/(float)TexHeight;

	// Write texture coordinates:
	pv=vert;
	pv->u=0.0f;  pv->v=0.00f;  pv++;
	pv->u=right; pv->v=0.00f;  pv++;
	pv->u=0.0f;  pv->v=bottom; pv++;
	pv->u=right; pv->v=bottom; pv++;

	unsigned char *lock=NULL;
	VertexBufferImage->Lock(0,sizeof(VertexList),&lock,0);
	memcpy(lock,VertexListImage,sizeof(VertexList));
	VertexBufferImage->Unlock();
	return;
}

void ImageSelectedDraw() {
	if(TexImage) {
		Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
		SetupMatrices();
		MakeVertexListImage();
		Device->SetTexture(0,TexImage);
		Device->SetStreamSource(0,VertexBufferImage,sizeof(CustomVertex));
		Device->SetVertexShader(D3DFVF_CUSTOMVERTEX);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Present();
	}
	else {
		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*)ImageMessage.c_str()), 320, 240, 640);
		FontGUI(ConvertCharStringToWCHAR((char*)"Press \"B\" to exit"), 320, 240 + vSpace, 640);
		Present();
	}
}

void DrawImageList() {
	int yDB = 110;
	DWORD color;
	int start = 0;

	if(ImageGameSelected > 7 && (ImageDatabase.size() > 15)) {
		start += (ImageGameSelected  - 7);
	}

	if((ImageGameSelected > ((ImageDatabase.size()-1) - 7)) && (ImageDatabase.size() > 15)) {
		start = (ImageDatabase.size() - 15);
	}

	for(int i = start; i <  start +15; i++) {
		if(i == ImageDatabase.size()) return;
		if(i ==ImageGameSelected) color = 0xffff00; else color = 0xffffff; 
		WCHAR atext2345[1024]={0};
		std::string t = ((ImageDBEntry)ImageDatabase[i]).name;
		for(int r = 0; r < 1024; r++) {
			if((t.c_str())[r] == '\0') {
				atext2345[r] = '\0';
				break;
			}
			atext2345[r] = (t.c_str())[r];
		}
		FontSetColour(color);
		FontCenteredText(atext2345, MenuPosX, yDB, 640);
		yDB+=20;
	}
}

void ImageListDraw() {
	FontSetColour(0xffff00);
	Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
	//Device->SetTexture(0,TexOption);
	SetupMatrices();
	MakeVertexListMenu();
	//Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
	DrawImageList();
	Present();
}

void ImageListDeleteDraw() {
	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*)"Delete image file?"), 320, 240, 640);
	FontGUI(ConvertCharStringToWCHAR((char*)"Press \"B\" to cancel or press \"Y\" to confirm."), 320, 240 + vSpace, 640);
	Present();
}

void ImageDraw() {
	if(ImageSelected == 1) {
		ImageSelectedDraw();
		return;
	}

	if(ImageList == 1) {
		ImageListDraw();
		return;
	}

	if(ImageListDelete == 1) {
		ImageListDeleteDraw();
		return;
	}
}

void ImageInput() {
	if(ImageSelected == 1) {
		ImageSelectedInput();
		return;
	}

	if(ImageList == 1) {
		ImageListInput();
		return;
	}

	if(ImageListDelete == 1) {
		ImageListDeleteInput();
		return;
	}
}

void ImageMenu() {
	RomBrowser = 0;
	InitImage();
	DrawImageMenu = 1;
	ImageList = 1;
	ImageSelected = 0;
	ImageListDelete = 0;
	while(DrawImageMenu == 1) {
		updateEffect();
		ReadInput();
		ImageDraw();
		ImageInput();
	}
	CloseImageMenu();
}

void ImageSelectedMenu(char* gameSelected) {
	FontSetColour(0xffff00);
	Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
	SetupMatrices();
	MakeVertexListMenu();
    FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
	Present();
	RomBrowser = 1;
	FreeImage();
	char fileName[260];
	gameName = gameSelected;
	ImageCategorySelected = 0;
	sprintf(fileName,"%s%s%s", "D:\\Images\\cpanel\\", (char*)gameName.c_str(), ".png");	
	if(!LoadEmulationImage(fileName)) {
		ImageCategorySelected++;
		sprintf(fileName,"%s%s%s", "D:\\Images\\marquee\\", (char*)gameName.c_str(), ".png");
		if(!LoadEmulationImage(fileName)) {
			ImageCategorySelected++;
			sprintf(fileName,"%s%s%s", "D:\\Images\\cabinet\\", (char*)gameName.c_str(), ".png");
			if(!LoadEmulationImage(fileName)) {
				ImageCategorySelected++;
				sprintf(fileName,"%s%s%s", "D:\\Images\\flyers\\", (char*)gameName.c_str(), ".png");
				if(!LoadEmulationImage(fileName)) {
					ImageCategorySelected++;
					sprintf(fileName,"%s%s%s", "D:\\Images\\snap\\", (char*)gameName.c_str(), ".png");
					if(!LoadEmulationImage(fileName)) {
						ImageCategorySelected++;
						sprintf(fileName,"%s%s%s", "D:\\Images\\title\\", (char*)gameName.c_str(), ".png");
						if(!LoadEmulationImage(fileName)) {
							while(true) {
								updateEffect();
								ReadInput();
								if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
									CancelSound();
									CloseImageMenu();
									return;
								} 
								FontSetColour(0xffff00);
								Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
								SetupMatrices();
								MakeVertexListMenu();
								//Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
								FontGUI(ConvertCharStringToWCHAR((char*)"No images found"), 320, 240, 640);
								FontGUI(ConvertCharStringToWCHAR((char*)"Press \"B\" to exit"), 320, 240 + vSpace, 640);
								Present();
							}
						}
					}
				}
			}
		}
	}
	ImageSelected = 1;
	Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	while(ImageSelected == 1) {
		updateEffect();
		ReadInput();
		ImageDraw();
		ImageInput();
	}
	CloseImageMenu();
}