// Driver Init module
#include "fba.h"
#include "unzip.h"
int bDrvOkay = 0;		// 1 if the Driver has been init'd okay, and it's okay to use the BurnDrv functions

char szAppRomPaths[4][260] = {{"d:\\roms\\"}, {"..\\roms\\"}, {""}, {""}};

static bool bSaveRAM = false;

static int DoLibInit() // Do Init of Burn library driver
{
	int i;
	int nRet;
	// HyperYagami: we need 16 entries
	static char *szRomName[BZIP_MAX * 4];

	memset(&szRomName, 0, sizeof(szRomName));

	for (i = 0; i < BZIP_MAX; i++) {
		char *szName;

		if (BurnDrvGetZipName(&szName, i)) {
			break;
		}

		for (int j = 0; j <= 3; j++) {
			// Allocate space for each full pathname
			if ((szRomName[i * 4 + j] = (char *)malloc(strlen(szName) + strlen(szAppRomPaths[j]) + 1)) != NULL) {
				// Use path plus default zip file name
				sprintf (szRomName[i * 4 + j], "%s%s", szAppRomPaths[j], szName);
				// Point bzip to it
				szBzipName[i * 4 + j] = szRomName[i * 4 + j];
			} else {
				continue;
			}
		}
	}
	szBzipName[i * 4] = NULL;		// Mark end of zip name list

	// Open the zip file(s) and check if they are okay
	BzipOpen(FALSE);
	
	// If there is an error with the romset, report it
	if (nBzipError) {
		}

	nRet = BurnDrvInit();
 
	BzipClose();
	for (i = 0; i < BZIP_MAX * 4; i++) {
		// Free the names of each pathnames
		if (szRomName[i] != NULL) {
			free(szRomName[i]);		// Free the strings
		}
		szRomName[i] = NULL;
		szBzipName[i] = NULL;		// Blank BZip list
	}
	szBzipName[i] = NULL;			// Mark end of zip name list
	
	if (nRet) {						// Init the driver
		return 1;
		} else {
		return 0;
	}
}

int DrvInit(int nDrvNum)
{

	int nRet;

// DrvExit() was causing Batrider to lock the 2nd time it was loaded
//	DrvExit();						// Make sure exitted

	nBurnDrvSelect = nDrvNum;		// Set the driver number
	
	AudSoundInit();						// Init DSound (not critical if it fails)

	nBurnSoundRate = 0;					// Assume no sound
	pBurnSoundOut = NULL;
	if (bAudOkay) {
		nBurnSoundRate = nAudSampleRate;
		nBurnSoundLen = nAudSegLen;
		AudSoundPlay();
		nAppVirtualFps = nBurnFPS;
	}
	
	nRet = DoLibInit();				// Init the Burn library's driver

	if (nRet) {
		//problem here
		BurnDrvExit();				// Exit the driver
		return 1;
	}

	GameInpInit();					// Init game input
	GameInpDefault();


	bDrvOkay = 1;					// Okay to use the BurnDrv functions

	bSaveRAM = false;

	// Init the video plugin
	nRet = VidInit();
	
	if (nRet) {
		return 1;
	}

	nBurnLayer = 0xFF;				// show all layers
	
	pBurnSoundOut = nAudNextSound;

	VidXboxLoadScreenData();		// Load the screen.cfg file and see if a user has their screensize set
									// otherwise use defaults
	
	return 0;
}

int DrvExit()
{
	
	nBurnSoundRate = 0;				// Blank sound
	pBurnSoundOut = NULL;

	VidExit();
	
	AudSoundStop();
	AudSoundExit();
	
	VidXboxSaveScreenData();		// save last set screen config
	BurnDrvExit();				    // Exit the driver
	bDrvOkay = 0;					// Stop using the BurnDrv functions
	 
	nBurnDrvSelect = ~0U;			// no driver selected

	return 0;
}



