// Driver Init module
#include "burner.h"
#include <xtl.h>
extern "C" int dprintf(char *format, ...);
int bDrvOkay = 0;						// 1 if the Driver has been initted okay, and it's okay to use the BurnDrv functions
TCHAR szAppRomPaths[DIRS_MAX][260] = { { _T("") }, { _T("") }, { _T("") }, { _T("") }, { _T("") }, { _T("") }, { _T("") }, { _T("D:\\roms\\") } };
static bool bSaveRAM = false;
bool OutOfMemory = false;

int DrvExit()
{

	if (nBurnDrvSelect < nBurnDrvCount) {
		if (bSaveRAM) {
			bSaveRAM = false;
		}
		ConfigGameSave(bSaveInputs);

		GameInpExit();				// Exit game input
		BurnDrvExit();				// Exit the driver
	}

	BurnExtLoadRom = NULL;
	bDrvOkay = 0;					// Stop using the BurnDrv functions
	nBurnDrvSelect = ~0U;			// no driver selected
	return 0;
}

static int DoLibInit()					// Do Init of Burn library driver
{
	int nRet = 0;

	////dprintf("BzipOpen(0); START\n");
	BzipOpen(0);
	////dprintf("BzipOpen(0); END\n");
	// If there is a problem with the romset, report it
	switch (BzipStatus()) {
		case BZIP_STATUS_BADDATA: {
			////dprintf("Bad Zip\n");
			BzipOpen(0);
			break;
								  }
		case BZIP_STATUS_ERROR: {
			////dprintf("Bad Zip\n");
			BzipClose();
			return 1;
								}
		default: {
				 }
	}

	////dprintf("BurnDrvInit(); START\n");
	nRet = BurnDrvInit();
	//if(OutOfMemory) {
	//	return -1;
	//}
	////dprintf("BurnDrvInit(); END\n");
	BzipClose();

	if (nRet) {
		return 3;
	} else {
		return 0;
	}
}

// Catch calls to BurnLoadRom() once the emulation has started;
// Intialise the zip module before forwarding the call, and exit cleanly.
static int __cdecl DrvLoadRom(unsigned char* Dest, int* pnWrote, int i)
{
	int nRet = 0;
	BzipOpen(0);
	BurnExtLoadRom(Dest, pnWrote, i);
	BzipClose();
	BurnExtLoadRom = DrvLoadRom;
	return nRet;
}

int DrvInit(int nDrvNum, bool bRestore)
{
	//dprintf("DrvInit Start\n");
	int nStatus;
	nBurnDrvSelect = nDrvNum;		// Set the driver number
	// Define nMaxPlayers early; GameInpInit() needs it (normally defined in DoLibInit()).
	nMaxPlayers = BurnDrvGetMaxPlayers();
	nStatus = DoLibInit();			// Init the Burn library's driver
	BurnExtLoadRom = DrvLoadRom;
	bDrvOkay = 1;					// Okay to use all BurnDrv functions
	bSaveRAM = false;
	nBurnLayer = 0xFF;				// show all layers
	//dprintf("DrvInit End\n");
	return 0;
}

int DrvInitCallback()
{
	return DrvInit(nBurnDrvSelect, false);
}
