//#define USE_DEBUGCLIENT
#define LAUNCHABLE_MEDIA

#include <XBApp.h>
#include <XBFont.h>
#include <XBHelp.h>
#include <XBSound.h>
#include <xgraphics.h>
#include <assert.h>
#include <d3d8perf.h>
#include "SndXBOX.hxx"
#include "CDDAXbox.h"
#include <stdio.h>
#include <vector>
#include "zlib.h"
//#include "unzip.h"
#include "debugclient.h"
#include "Mp3Player.h"
#include "undocumented.h"
#include "iosupport.h"
#include "panel.h"
#include "fonthelper.h"
#include "plaything.h"
#include "smb++.h"
#include "custom_launch_params.h"
#include "colormap.h"
#include "arrow.h"
#include "numpad.h"
#include "numpadsegag.h"
#include "png.h"
//#include "SDL.h"
#include "lightgun.h"
#include "src\\gens\\ggenie.h"
#include "gamescreen.h"

#define NEED_CDDA
//#define USE_DEBUGCLIENT
#define GAME_GENIE

#include "src\Gens\io.h"
#include "src\Gens\vdp_io.h"
#include "src\Gens\blit.h"
#include "src\Gens\save.h"
#include "src\Gens\Mem_M68k.h" 
#include "src\Gens\cd_sys.h"
#include "src\Gens\vdp_rend.h" 

extern int Gens_Running ;

int PASCAL gensmain( char *romfilename, int country, int whichCD, int realCD, int sambaIsoBin, int relaxIsoBin,
					int xb_Fast_Blur,
					int xb_Sprite_Over,
					int xb_YM2612_Improv,
					int xb_DAC_Improv,
					int xb_PSG_Improv,
					int xb_MSH2_Speed,
					int xb_SSH2_Speed,
					int xb_Show_LED );
void genie_decode(const char* code, struct patch* result) ;

#ifdef __cplusplus
extern "C" {
#endif

int alwaysOff ;
int missVBlank ;
extern int sounddanger ;
float FPS = 60 ;
float desiredFPS =60 ;

int throttle ;
int loaded_cue ;
int blittermode ;
int changedblit ;
int multiport =0;
int sleepamount ;

#include "writepng.h"

int Init_2xSaI(uint32 BitFormat) ;
void _2xSaI(uint8 *srcPtr, uint32 srcPitch,
		 uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void _2xSaIScanline(uint8 *srcPtr, uint32 srcPitch,
		 uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperEagle(uint8 *srcPtr, uint32 srcPitch,
		uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperEagleScanline(uint8 *srcPtr, uint32 srcPitch,
		uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Super2xSaI(uint8 *srcPtr, uint32 srcPitch,
		 uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Super2xSaIScanline(uint8 *srcPtr, uint32 srcPitch,
		 uint8 *deltaPtr,
		 uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Scale2x(uint8 *srcPtr, uint32 srcPitch,
	     uint8 *deltaPtr,
	     uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperScale(uint8 *srcPtr, uint32 srcPitch,
	     uint8 *deltaPtr,
	     uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperScaleScanline(uint8 *srcPtr, uint32 srcPitch,
	     uint8 *deltaPtr,
	     uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Eagle(uint8 *srcPtr, uint32 srcPitch,
	     uint8 *deltaPtr,
	     uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void EagleScanline(uint8 *srcPtr, uint32 srcPitch,
	     uint8 *deltaPtr,
	     uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);

void Simple2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */,
              unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanlines) ;
void AdMame2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */,
              unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanline) ;

unsigned int xbox_get_pitch();
unsigned char * xbox_get_screen_buffer() ;
int xbox_read_sector_type( unsigned int sector, unsigned int sector_type ) ;
void sprintfx( const char *fmt, ... );

//_CRTIMP extern int * __cdecl _errno(void);
char gxmsg[2000] ;
extern char *psxM;

int errno ;

#ifdef __cplusplus
}
#endif


extern "C"
{
void hq3x_32(unsigned char*, unsigned char*, DWORD, DWORD, DWORD, DWORD, DWORD);
unsigned int   LUT16to32[65536];
unsigned int   RGBtoYUV[65536];
}



#pragma warning(disable:4244)
#pragma warning(disable:4018)
#pragma warning(disable:4101)

#define PLATFORM_NAME "GENESIS"
#define PLATFORM_SAV L"SGENSAV"
#define READING_ROMS_STRING L"Reading sgenroms directory...please wait."
#define PLATFORM_INI "neogenesis.ini"
#define PLATFORM_MEMORY_POINTER Ram_68k
#define THEMEMUSIC "D:\\SGENROMS\\SGENTHEME.MP3"
#define PLATFORM_FILE_DIR m_defaultRomDir
#define CONSOLE_MEMORY_SIZE 0x10000
#define DEFAULT_PARENT_DIR "D:\\sgenroms\\*"
#define PLAYTHING_INI "plaything.cfg"
#define CD_BUF_SECTORS 20
#define CD_DATA_BUFFER_SIZE CD_BUF_SECTORS*2352
#define MLINE(x) ((float)( 80 + (( pmenuParams->lineHeight-2 ) * (x)) ))
#define PROJECTILE_DEF 4 
#define DEFAULT_SKIN "default_neogenesis"
#define DEFAULT_SKIN_DIR "D:\\EMUSKINS"
#define DEFAULT_SAVE_PATH "E:\\SAVES\\NEOGENESIS"
#define MAIN_MENU_STRING L"NeoGenesis Main Menu"
#define EMU_RECORDING_SIZE ( sizeof(DWORD)*4*60*60*10 )
#define CD_SECS 60
#define CD_FRAMES 75


unsigned char *m_memory_locations[] = { Ram_68k  } ;
unsigned int  m_memory_sizes[] = { 0x10000 } ;

#define NUM_MEMORY_LOCATIONS 1

int CODE_LENGTHS[] = { 12 } ;



#define PACKED

#pragma pack(1)

typedef struct
{
  BYTE rsvd;
  BYTE ADR;
  BYTE trackNumber;
  BYTE rsvd2;
  BYTE addr[4];
}
PACKED TOCTRACK;

typedef struct
{
  WORD tocLen;
  BYTE firstTrack;
  BYTE lastTrack;
  TOCTRACK tracks[100];
}
PACKED TOC, *PTOC, FAR * LPTOC;

#pragma pack()

#define METHOD_BUFFERED                   0
#define METHOD_OUT_DIRECT     2
//#define FILE_READ_ACCESS                  0x00000001
#define FILE_DEVICE_CD_ROM                0x00000002

#define IOCTL_CDROM_BASE                FILE_DEVICE_CD_ROM
//#define CTL_CODE(DeviceType,Function,Method,Access) (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))

#define IOCTL_CDROM_READ_TOC         CTL_CODE(IOCTL_CDROM_BASE, 0x0000, METHOD_BUFFERED, FILE_READ_ACCESS)




typedef struct
{

	unsigned int mapping ;
	unsigned int moves[32] ;
	unsigned char endmove ;
	unsigned char delay ;
	unsigned char currmove ;
	unsigned char currdelay ;
} COMBO ;

typedef struct
{
	unsigned int analog_sensitivity ;
	unsigned int emu_buttons[32] ;
	unsigned char emu_buttons_autofire[32] ;
	unsigned char emu_buttons_autofire_last[32] ;
	unsigned int emu_buttons_definition[32] ;
	unsigned int sfx_vol_up ;
	unsigned int sfx_vol_down ;
	unsigned int bgm_vol_up ;
	unsigned int bgm_vol_down ;
	unsigned int throttle ;
	unsigned int save_state ;
	unsigned int load_state ;
	unsigned int change_save_slot ;
	unsigned int screenshot ;
	unsigned int options_menu ;
	unsigned int change_gfx_filter;
	unsigned int toggle_bgm ;
	unsigned int start_recording ;
	unsigned int stop_recording ;
	unsigned int start_playing ;
	unsigned int stop_playing ;
	unsigned int capture_mode ;
	COMBO combos[10] ;

} MAPPINGS ;

typedef struct _PLAYTHING_CONFIG
{
	SPRITE_PARAMS sprites[20] ;
	EFFECT_PARAMS effects[3] ;

} PLAYTHING_CONFIG ;

typedef struct _MENU_PARAMS
{
	char bkg[100] ;
	CPanel *panel ;
	int  transparency ;
	int  borderWidth ;
	int  halign ;
	int  valign ;
	int  offsetx ;
	int  offsety ;
	int  maxTextWidth ;
	int  maxNumLines ;
	DWORD normalColor ;
	DWORD selectedColor ;
	DWORD selectedAndNotedColor ;
	DWORD notedColor ;
	DWORD selectBarColor ;
	unsigned int  size ;
	unsigned int  lineHeight; 
	int screenshotX ;
	int screenshotY ;
	int screenshotW ;
	int screenshotH ;
	int screenshotTransparency ;
	int animationDelay ;

	PLAYTHING_CONFIG ptConfig ;

} MENU_PARAMS ;

typedef struct _SKIN_PARAMS
{
	char loadEmuSplash[100] ;
	char loadGameSplash[100] ;
	char menuMoveSound[100] ;
	char menuCancelSound[100] ;
	char menuSelectSound[100] ;
	char menuBkgMusic[100] ;
	char font[100] ;
	int  fade ;
	int  loopbgm ;

	MENU_PARAMS mainMenu ;
	MENU_PARAMS gameSelectMenu ;
	MENU_PARAMS otherMenu ;
	MENU_PARAMS popupMenu ;
	MENU_PARAMS loadingMenu ;

} SKIN_PARAMS ;

typedef struct _BUTTON_DEFINITION
{
	char name[40] ;
	unsigned int  value ;
} BUTTON_DEFINITION ;


#define XBOX_DPAD_UP          0x00000001
#define XBOX_DPAD_DOWN        0x00000002
#define XBOX_DPAD_LEFT        0x00000004
#define XBOX_DPAD_RIGHT       0x00000008
#define XBOX_START            0x00000010
#define XBOX_BACK             0x00000020
#define XBOX_LEFT_THUMB       0x00000040
#define XBOX_RIGHT_THUMB      0x00000080

#define XBOX_A                0x00000100
#define XBOX_B                0x00000200
#define XBOX_X                0x00000400
#define XBOX_Y                0x00000800
#define XBOX_BLACK            0x00001000
#define XBOX_WHITE            0x00002000
#define XBOX_LEFT_TRIGGER     0x00004000
#define XBOX_RIGHT_TRIGGER    0x00008000

#define XBOX_LTHUMB_UP        0x00010000
#define XBOX_LTHUMB_DOWN      0x00020000
#define XBOX_LTHUMB_LEFT      0x00040000
#define XBOX_LTHUMB_RIGHT     0x00080000

#define XBOX_RTHUMB_UP        0x00100000
#define XBOX_RTHUMB_DOWN      0x00200000
#define XBOX_RTHUMB_LEFT      0x00400000
#define XBOX_RTHUMB_RIGHT     0x00800000


	BUTTON_DEFINITION g_xboxButtonDefinitions[] = {
		{ "DPad Up", XBOX_DPAD_UP },
		{ "DPad Down", XBOX_DPAD_DOWN },
		{ "DPad Left", XBOX_DPAD_LEFT },
		{ "DPad Right", XBOX_DPAD_RIGHT },
		{ "Start", XBOX_START },
		{ "Back", XBOX_BACK },
		{ "Left Thumb", XBOX_LEFT_THUMB },
		{ "Right Thumb", XBOX_RIGHT_THUMB },
		{ "A", XBOX_A },
		{ "B", XBOX_B },
		{ "X", XBOX_X },
		{ "Y", XBOX_Y },
		{ "Black", XBOX_BLACK },
		{ "White", XBOX_WHITE },
		{ "LTrigger", XBOX_LEFT_TRIGGER },
		{ "RTrigger", XBOX_RIGHT_TRIGGER },
		{ "LThumb Up", XBOX_LTHUMB_UP },
		{ "LThumb Down", XBOX_LTHUMB_DOWN },
		{ "LThumb Left", XBOX_LTHUMB_LEFT },
		{ "LThumb Right", XBOX_LTHUMB_RIGHT },
		{ "RThumb Up", XBOX_RTHUMB_UP },
		{ "RThumb Down", XBOX_RTHUMB_DOWN },
		{ "RThumb Left", XBOX_RTHUMB_LEFT },
		{ "RThumb Right", XBOX_RTHUMB_RIGHT },
		{ "Nothing", 0 },
	} ;

#define NUM_XBOX_BUTTONS ( sizeof( g_xboxButtonDefinitions ) / sizeof(BUTTON_DEFINITION) )


#define JOY_A        0x0001
#define JOY_B        0x0002
#define JOY_C        0x0004
#define JOY_X        0x0008
#define JOY_Y        0x0010
#define JOY_Z        0x0020
#define JOY_UP       0x0040
#define JOY_DOWN     0x0080
#define JOY_LEFT     0x0100
#define JOY_RIGHT    0x0200
#define JOY_START    0x0400
#define JOY_MODE     0x0800




	BUTTON_DEFINITION g_emuButtonDefinitions[] = {
		{ "A", JOY_A },
		{ "B", JOY_B },
		{ "C", JOY_C },
		{ "X", JOY_X },
		{ "Y", JOY_Y },
		{ "Z", JOY_Z },
		{ "Up", JOY_UP },
		{ "Down", JOY_DOWN },
		{ "Left", JOY_LEFT },
		{ "Right", JOY_RIGHT },
		{ "Start", JOY_START },
		{ "Mode", JOY_MODE },
		{ "Nothing", 0 },
	} ;

#define NUM_EMU_BUTTONS ( sizeof( g_emuButtonDefinitions ) / sizeof(BUTTON_DEFINITION) )


#define DEFAULT_BUTTON1  XBOX_A
#define DEFAULT_BUTTON2  XBOX_B
#define DEFAULT_BUTTON3  XBOX_BLACK
#define DEFAULT_BUTTON4  XBOX_X
#define DEFAULT_BUTTON5  XBOX_Y
#define DEFAULT_BUTTON6  XBOX_WHITE
#define DEFAULT_BUTTON7  XBOX_DPAD_UP
#define DEFAULT_BUTTON8  XBOX_DPAD_DOWN
#define DEFAULT_BUTTON9  XBOX_DPAD_LEFT
#define DEFAULT_BUTTON10 XBOX_DPAD_RIGHT
#define DEFAULT_BUTTON11 XBOX_START
#define DEFAULT_BUTTON12 XBOX_BACK
#define DEFAULT_BUTTON13 0
#define DEFAULT_BUTTON14 0
#define DEFAULT_BUTTON15 0
#define DEFAULT_BUTTON16 0
#define DEFAULT_BUTTON17 0
#define DEFAULT_BUTTON18 0
#define DEFAULT_BUTTON19 0
#define DEFAULT_BUTTON20 0
#define DEFAULT_BUTTON21 0
#define DEFAULT_BUTTON22 0
#define DEFAULT_BUTTON23 0
#define DEFAULT_BUTTON24 0
#define DEFAULT_BUTTON25 0
#define DEFAULT_BUTTON26 0
#define DEFAULT_BUTTON27 0
#define DEFAULT_BUTTON28 0
#define DEFAULT_BUTTON29 0
#define DEFAULT_BUTTON30 0
#define DEFAULT_BUTTON31 0
#define DEFAULT_BUTTON32 0


typedef struct _cheat_code {
	char code[20] ;
	byte type ;
	UINT32 adr ;
	UINT32 val ;
	byte   enabled ;
	char desc[100] ;
} CHEAT_CODE;

typedef struct _NETPLAY_SERVER {
	char ip[16] ; 
} NETPLAY_SERVER;

typedef struct _favoritestruct {
	char filename[MAX_PATH] ;
} FAVORITE ;


//int errno ;

//-----------------------------------------------------------------------------
// Name: class CXBoxSample
// Desc: Main class to run this application. Most functionality is inherited
//       from the CXBApplication base class.
//-----------------------------------------------------------------------------
class CXBoxSample : public CXBApplication
{
public:
    CXBoxSample();

    virtual HRESULT Initialize();
    virtual HRESULT InitializeWithScreen();
    virtual void    InitializeEmuSpecific();
    virtual HRESULT Render();
    virtual HRESULT FrameMove();
	virtual void MoveCursor() ;
	virtual void    initConsole( UINT32 idx, int isFavorite) ;
	virtual void    cleanupConsole( ) ;
	virtual int     handleEvents() ;
	virtual int     init_texture() ;
	virtual BOOL    SetRefreshRate(INT iRefreshRate);
	virtual int		init_white_texture();
	virtual int		render_to_texture() ;
	virtual void	FindAvailRoms(char *dir) ;
	void            renderMenuText( int selectable, int selected, WCHAR **lines, int numlines, int isPopup ) ;
	int             renderMenuTextWrapper( int selectable, int selected, WCHAR **lines, int numlines, int isPopup, CPanel *panel, int menuChoice, int dualColumn, int colSpacing ) ;
	void            renderDualMenuText( int selectable, int selected, WCHAR **lines, int numlines, int isPopup, int colSpacing ) ;
	int             getValuePopup( char *title, int oldValue, int minval, int maxval, CPanel *panel );
	virtual void    doStartSearchMenu() ;
	virtual void	saveKeys( char *keyfile ) ;
	virtual void	loadKeys( char *keyfile ) ;
	virtual void    doCodeListMenu() ;
	virtual int     receiveNetworkData( );
	virtual void    xboxStartRecording() ;
	virtual void    xboxStopRecording() ;
	virtual void    xboxStartPlaying() ;
	virtual void    xboxStopPlaying() ;
	virtual void    xboxOptionsMenu() ;
	virtual void    doChangeHWFilter() ;
	virtual void    doChangeSWFilter() ;
	virtual void    doChangeVideoMode() ;
	virtual void    doPlaythingClear( );
#ifdef LIGHTGUN
	virtual void    doCalibrateLightgun( );
#endif
	virtual void    saveSettings( char *filename );
	virtual int     loadSettings( char *filename );
	virtual void    doAutofireConfig( int port );
	virtual void    doMainMenu() ;
	virtual void    copyOldSaves();
	virtual int     validateCode( char *code, CHEAT_CODE *ccode, int codetype ) ;
	virtual void    checkGeneralEvents() ;
	virtual void    loadControllerSettings( char *buf ) ;
	virtual void    saveControllerSettings( FILE *outfile ) ;
	virtual void    doManageCheatCode( int selected );
	virtual void    doConfigureSkin() ;
	virtual void    doEditGameGenie( int selected ) ;
	virtual int     addGameGenieCode() ;
	virtual void    doBrowseScreenshots( ) ;
	void            loadMostRecentSaveState( );
	virtual void    performEmuSpecificOption( int start, int menuChoice ) ;
	int             addEmuSpecificOptions( int start ) ;
	virtual int		showScreenshot( int screenNum, int currSelection, int onlyFavorites, MENU_PARAMS *menu ) ;
	virtual void    saveGameSpecificSettings() ;
	virtual void    doGraphicsFiltering() ;
	virtual void    doSelectColor( DWORD *pColor, MENU_PARAMS *menuParams );
	virtual void    doTransition( CPanel *pnl1, CPanel *pnl2, int speed, int effect ) ;
	virtual void    emuLaunch( unsigned int gameSelected, unsigned int isFavorite ) ;
	virtual void    getNewRoot( char *szRoot) ;
	unsigned int    getNewDefinition( unsigned int oldMapping );
	unsigned int    doSelectGame( int onlyFavorites, int canChangeDir ) ;
	virtual void    doConfigureGame( char *settingsfile, char *keysfile ) ;
	virtual void    SetupPlaything( );
	virtual void    loadCueSheet( char *cuefile ) ;
	virtual void    doSelectBackground( char *bkgfile, CPanel *ppanel ) ;
	virtual void    doSelectSound( char *soundfile, CXBSound *psound ) ;
	virtual void    doSelectBGM( char *bgmfile ) ;
	virtual void    doSelectFont( char *fontfile ) ;
	virtual void    doConfigureSkinMenu( MENU_PARAMS *menuparams, char *title ) ;
	virtual void    doMenuBackgroundSettings( MENU_PARAMS *menuparams) ;
	virtual void    doMenuTextSettings( MENU_PARAMS *menuparams) ;
	virtual void    doMenuSpriteSettings( MENU_PARAMS *menuparams) ;
	virtual void    doScreenshotSize( MENU_PARAMS *menu );
	virtual void    updateEmuSpecificCheats() ;
	virtual void    doSavePlaything() ;
	virtual int     setupNetplay() ;
	virtual void    doLoadPlaything() ;
	virtual void    renderPopupBkg( int numlines ) ;
	unsigned int    getNewMapping( unsigned int oldMapping ) ;
	virtual void    doConfigureControllers() ;
	virtual void    doConfigureController( int port ) ;
	virtual void    doEmulatorDefinitions( int port ) ;
	virtual void    doJoypadMappings( int port ) ;
	unsigned int    getNewEmuMapping( unsigned int port, unsigned int combo, unsigned int oldMapping );
	virtual void    doChangeCombo( int port, int combo );
	virtual void    doChangeComboMoves( int port, int combo );
	virtual void    doComboConfig( int port );
	virtual void    doGameJoypadMappings( int port ) ;
	virtual void    doUIJoypadMappings( int port ) ;
	virtual void    doAddFoundCodes() ;
	virtual void    doContinueSearchMenu() ;
	virtual void    doCodeListMenu2() ;
	virtual int     pollXBoxControllers( );
	virtual int     pollNetworkControllers( );
	virtual void    doAddFoundCodes2() ;
	virtual void    changeMenu( MENU_PARAMS *menuparams1, MENU_PARAMS *menuparams2 ) ;
	virtual void    doConfigureSprite( MENU_PARAMS *menuparams, int which ) ;
	virtual void    doConfigureEffects(MENU_PARAMS *menuparams, int which) ;
	virtual void    doEditCode2( int selected, int numpositions, int codetype ) ;
	virtual void    doContinueSearchMenu2() ;
	virtual void	popupMsg( char *msg, CPanel *panel, int onetime=0 ) ;
	virtual void    doCheatMenu() ;
	virtual void    doEmulatorOptions() ;
	virtual void    doFontSize() ;
	virtual void    xboxSaveState() ;
	virtual void    xboxThrottle( int throttle ) ;
	virtual void    xboxLoadState() ;
	virtual void    xboxChangeFilter() ;
	virtual void    xboxScreenshot() ;
	virtual void    xboxChangeState() ;
	virtual void    doLoadSkin( char *skinname, int forceRoot ) ;
	virtual void    doSaveSkin( ) ;
	virtual void    loadSkinMenuSettings( char *szbuf, char *basesection, MENU_PARAMS *menu );
	virtual void    saveSkinMenuSettings( FILE *outfile, char *basesection, MENU_PARAMS *menu );
	virtual void    doSelectSkin() ;
	virtual void    doLoadIni( int forceRoot ) ;
	virtual void    doSaveIni() ;
	virtual void    doLoadEmuSpecificIni( char *szbuf) ;
	virtual void    doSaveEmuSpecificIni( FILE *outfile ) ;
	virtual void    doSaveConfig() ;
	virtual void    doScreenSize() ;
	virtual void    doNetplayOptions();
	virtual void    addNewNetplayServer( );
	virtual void    saveFavorites();
	virtual void    addFavorite( char *favorite ) ;
	virtual void    removeFavorite( unsigned int whichfav) ;
	virtual void    loadFavorites();
	virtual int     yesNoMenu( char *msg, CPanel *panel ) ;
	virtual int     selectNetplayServer() ;
	virtual void    doTextOffset() ;
	virtual void    doLoadNewDisk();
	virtual void    doGraphicsFixes();
	virtual void    doCPUFixes();
	void            ClearScreen() ;
	void            doSelectMemcards();
	virtual void    doCDGame( ) ;
	virtual void    doConfiguration() ;
	virtual void    updateCheats() ;
	virtual void    updateCheats2() ;
	virtual void    processEmu( BOOL render ) ;
	virtual void    fillPresentationParams() ;
	virtual void    ggenie_init() ;
	virtual void    cht_load() ;
	virtual void    cht_save() ;
	virtual void    deleteSaveFiles( int which ) ;
	virtual void    doEditCode( int which ) ;
	virtual BOOL    hasFiles( int which ) ;
	virtual int     rom_load_zip( char *hugozipfile ) ;
	virtual void    QuickSort( int start, int end ) ;
	void			MenuBar( int xpos, int ypos, int xlen, int ylen ) ;
	void			ColorBar( int xpos, int ypos, int xlen, int ylen, DWORD color ) ;

typedef struct
    {
     unsigned char beg_min;
     unsigned char beg_sec;
     unsigned char beg_fra;

     unsigned char type;

     unsigned int beg_lsn;
     unsigned int length;

     char filename[256];


     } Track;
	Track CD_track[0x100];
	int   nb_max_track ;
	

	int m_bOKToDraw ;
	int m_countryCode ;
	int m_cdMethod ;
	int xbox_Fast_Blur;
	int xbox_Sprite_Over;
	int xbox_YM2612_Improv;
	int xbox_DAC_Improv;
	int xbox_force_fixtear ;
	int xbox_PSG_Improv;
	int xbox_MSH2_Speed;
	int xbox_SSH2_Speed;
	int xbox_Show_LED;

	DWORD m_xboxControllers[4] ;
	DWORD m_prevEmuControllers[4] ;
	DWORD m_emuControllers[4] ;
	DWORD m_networkEmuControllers[4] ;
	DWORD m_networkStatus ;
	NETPLAY_SERVER m_netplayServers[32] ;
	char m_screenshotDir[MAX_PATH] ;
	int m_defaultScreenshots ;

	int m_changedGenie ;

	D3DXVECTOR2 m_gameVecScale ; 
	D3DXVECTOR2 m_gameVecTranslate ; 
	RECT m_gameRectSource ;

	CRelax m_relaxTracks[99] ;
	SMB m_smb;
	Util m_smbUtil ;
	int m_stateNumber ;
	int  m_smbCdFile ;
	int  m_bUsingSamba ;
	int m_xboxHFilter ;
	int m_xboxSFilter ;
	char m_smbShare[500] ;
	float m_fFrameTime ;
	UINT32 m_numFrames ;
	DWORD m_startTime ;
	int  m_scrollSpeed ; 
	int   keyTime ;
	unsigned int m_pitch ;
	unsigned int m_pitchHQ ;
	DWORD  m_bRealCD ;
	DWORD  m_currentStartSector ;
	unsigned char *m_ptrCdBuf ;
	char m_cdromID[11]; 
	DWORD m_bitDepth ;
	DWORD m_lineHeight ;
	unsigned int m_biosMode ;
	unsigned int m_vandalFix ;
	unsigned int m_psxfix_Xa ;
	unsigned int m_psxfix_Sio ;
	unsigned int m_psxfix_Mdec ;
	unsigned int m_psxfix_Cdda ;
	unsigned int m_psxfix_Cpu ;
	unsigned int m_psxfix_SpuIrq ;
	unsigned int m_psxfix_VSyncWA ;
	CXBSocket m_sockListener ;
	CDebugClient m_sockNetplay;
	int       m_bNetplay ;
	unsigned int m_bNetworkCD ;
	char m_szSkin[100] ;
	char m_szSkinDir[MAX_PATH] ;
	SKIN_PARAMS m_skin ;
	MENU_PARAMS *pmenuParams ;


	unsigned int m_changedSettings ;
	WCHAR *m_menuText[200] ;

	CPlayThing m_plaything ;



	//PLAYTHING_CONFIG m_ptConfig ;

	PLAYTHING_CONFIG m_ptConfig ;


	MAPPINGS m_mappings[4] ;

	UINT32 topIdx  ;
	UINT32 curr  ;
	CDebugClient m_debugClient ;
	D3DPalette			*m_pd3dPalette ;
	BOOL m_bIsDDrive ;
	CDDAXbox m_cdda ;

    CXBHelp     m_Help;             // Help object
    BOOL        m_bDrawHelp;        // TRUE to draw help screen
	D3DPRESENT_PARAMETERS	m_origPP ;


    LPDIRECTSOUND8      m_pDSound;      // DirectSound object
    DWORD               m_dwCurrent;    // Current surface
	DWORD               m_graphicsFixes ;
	DWORD               m_frameskip, m_framelimit ;
	DWORD				m_numtracks ;
	int m_bMappingCircle ;
	int m_bMappingSquare ;
	int m_bMappingTriangle ;
	int m_bMappingCross ;
	int m_bMappingR1 ;
	int m_bMappingL1 ;
	int m_bMappingR2 ;
	int m_bMappingL2 ;
	int m_bMappingStart ;
	int m_bMappingSelect ;
	int m_bMappingThrottle ;
	CPanel m_pnlBackgroundMain ;
	CPanel m_pnlBackgroundSelect ;
	CPanel m_pnlBackgroundOther ;
	CPanel m_pnlSplashEmu ;
	CPanel m_pnlSplashGame ;
	CPanel m_pnlPopup ;
	CPanel m_pnlGameScreen ;
	CPanel m_pnlGameScreenHQ ;

	CFontHelper m_Font ;

	byte *m_memBuf1, *m_memBuf2, *m_consoleMemory, *m_memMatches ;
	UINT32 m_currentMemMatches ;
	unsigned char *m_cdDataBuffer ;

	typedef struct _filenamestruct {
		WCHAR name[200] ;
		unsigned char filename[200] ;
		char isDir ;
	} FILENAME ;


	FILENAME *files ;
	FAVORITE *m_filesFavorites ;
	unsigned long m_numFavorites ;
	unsigned long numfiles ;
	UINT32   m_iMaxWindowList;
	UINT32   m_iWindowMiddle ;
	UINT32   m_steps ;
	DWORD    m_dwStartPause ;
	int		m_nbytes ;
	int		m_nXOffset, m_nYOffset, m_nFontHeight ;
	int		m_namesPerPage ;
	char    m_szCurrentDir[MAX_PATH];
	CIoSupport m_io ;
	HANDLE m_hCdrom ;
	TOC m_toc;
	unsigned char m_cdbuffer[2352*4] ;
	gzFile m_cdfile ;
	unsigned char m_memcard1[MAX_PATH] ;
	unsigned char m_memcard2[MAX_PATH] ;
	int m_memcardnum1, m_memcardnum2 ;
	unsigned char m_biosfile[100] ;


	LPDIRECT3DTEXTURE8	m_pd3dBackgroundTexture;
	LPDIRECT3DTEXTURE8	Texture;
	LPDIRECT3DTEXTURE8	TextureHQ;
	LPDIRECT3DTEXTURE8	WhiteTexture;
	LPD3DXSPRITE			Sprite;
	LPD3DXSPRITE			MenuSprite;
	byte*				g_pBlitBuff ;
	byte*				g_pAlignBuff ;
	byte*				g_pDeltaBuff ;
	int					m_droppedFrames ;	
	
	UINT32				m_state ;
    WCHAR      m_strMessage[80];
	UINT32              m_msgDelay ;


	SoundXBOX			m_sound;
	Mp3Player			m_mp3player;
	CXBSound			m_sfxMenuMove;
	CXBSound			m_sfxMenuSelect;
	CXBSound			m_sfxMenuCancel;
	char				g_savePath[500] ;
	char				g_saveprefix[500] ;
	char				g_sramfile[500] ;
	char				g_bramfile[500] ;
	char				g_cuefile[500] ;
	char				g_rtcfile[500] ;
	char				g_chtfile[500] ;
	char				g_statefile[500] ;
	char				g_keysfile[500] ;
	char				g_settingsfile[500] ;
	FILE                *m_logfile ;

// Indicates the width and height of the screen
	UINT32 theWidth;
	UINT32 theHeight;
	UINT32 theWidthHQ;
	UINT32 theHeightHQ;
    RECT SrcRect;
    RECT DestRect;

	int					m_nScreenX, m_nScreenY, m_nScreenMaxX, m_nScreenMaxY ;


	CHEAT_CODE *m_cheatCodes;

	typedef struct _cheatdbentry 
	{
		char gamename[100] ;
		char slus[11] ;
		unsigned int numcodes ;
		char *filepos ;
	} CHEATDBENTRY ;

	//CHEATDBENTRY m_cheatDB[5000] ;

	char *m_cheatfile ;
	unsigned int m_numDBCheats ;

	UINT32 m_numCheats ;


};

CDDAXbox  *g_cdda ;


#include "..\common\commonfuncs.cpp"


struct { char *keyname ; int keynum ; } validKeys[11] = 
{
	{ "XBOX A", 0 },
	{ "XBOX B", 1 },
	{ "XBOX X", 2 },
	{ "XBOX Y", 3 },
	{ "XBOX BLACK", 4 },
	{ "XBOX WHITE", 5 },
	{ "XBOX START", 6 },
	{ "XBOX BACK", 7 },
	{ "XBOX LTRIGGER", 8 },
	{ "XBOX RTRIGGER", 9 },
	{ "UNMAPPED", 10 },
};




void CXBoxSample::doLoadEmuSpecificIni( char *szbuf ) 
{

	//m_nXOffset = GetIniInt( szbuf, "GENERAL", "TEXT_OFFSET_X", 0 ) ;

}

void CXBoxSample::doSaveEmuSpecificIni( FILE *outfile ) 
{



}

void InitLUTs(void)
{
  int i, j, k, r, g, b, Y, u, v;

  for (i=0; i<65536; i++)
    LUT16to32[i] = ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3);

  for (i=0; i<32; i++)
  for (j=0; j<64; j++)
  for (k=0; k<32; k++)
  {
    r = i << 3;
    g = j << 2;
    b = k << 3;
    Y = (r + g + b) >> 2;
    u = 128 + ((r - b) >> 2);
    v = 128 + ((-r + 2*g -b)>>3);
    RGBtoYUV[ (i << 11) + (j << 5) + k ] = (Y<<16) + (u<<8) + v;
  }

}

int CXBoxSample::init_texture()
{
	InitLUTs() ;

	// Release any previous texture
	if (Texture) 
	{ 
		return 1 ;
		Texture->BlockUntilNotBusy() ;
		Texture->Release();
		Texture = NULL;
	}
	
	theWidth = 640 ;
	theHeight = 480 ;

	// Create the texture
	if (D3DXCreateTextureFromFileInMemoryEx(m_pd3dDevice, GAMESCREEN_FILE, sizeof(GAMESCREEN_FILE),
		 theWidth, theHeight, 1, 0, D3DFMT_LIN_R5G6B5, D3DPOOL_MANAGED,
		 //D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED,
		 D3DX_FILTER_NONE , D3DX_FILTER_NONE, 0, NULL, NULL, &Texture)==D3D_OK)
	{
		m_pnlGameScreen.m_pTexture = NULL ;
		if ( FAILED(m_pnlGameScreen.Create(m_pd3dDevice, Texture, FALSE, theWidth, theHeight)) )
		{
			popupMsg( "no create panel", &m_pnlBackgroundOther ) ;
		}
	}
	else
	{
		popupMsg( "no load texture", &m_pnlBackgroundOther ) ;
	}


	theWidthHQ = 320*3 ;
	theHeightHQ = 240*3 ;

	// Create the texture
	if (D3DXCreateTextureFromFileInMemoryEx(m_pd3dDevice, GAMESCREEN_FILE, sizeof(GAMESCREEN_FILE),
		 theWidthHQ, theHeightHQ, 1, 0, D3DFMT_LIN_X8R8G8B8, D3DPOOL_MANAGED,
		 //D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED,
		 D3DX_FILTER_NONE , D3DX_FILTER_NONE, 0, NULL, NULL, &TextureHQ)==D3D_OK)
	{
		m_pnlGameScreenHQ.m_pTexture = NULL ;
		if ( FAILED(m_pnlGameScreenHQ.Create(m_pd3dDevice, TextureHQ, FALSE, theWidthHQ, theHeightHQ)) )
		{
			popupMsg( "no create panel", &m_pnlBackgroundOther ) ;
		}
	}
	else
	{
		popupMsg( "no load texture", &m_pnlBackgroundOther ) ;
	}

	//D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_R5G6B5, D3DPOOL_DEFAULT, &Texture);
//	D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_X1R5G5B5, D3DPOOL_DEFAULT, &Texture);
	
	//Init_2xSaI( 555 ) ;

	//if ( FAILED(m_pnlGameScreen.Create( m_pd3dDevice, Texture ) ) )
	//{
		//sprintfx( "failed create game screen\r\n") ;
	//}
	


	D3DSURFACE_DESC desc;
    TextureHQ->GetLevelDesc(0, &desc);

	if (g_pBlitBuff != NULL)
	{
		delete [] g_pBlitBuff;
		g_pBlitBuff = NULL;
	}
	
	// Allocate a buffer to blit our frames to
	g_pBlitBuff = new byte[desc.Size];


	if (g_pAlignBuff != NULL)
	{
		delete [] g_pAlignBuff;
		g_pAlignBuff = NULL;
	}
	
	// Allocate a buffer to blit our frames to
	//g_pAlignBuff = new byte[desc.Size];

    Texture->GetLevelDesc(0, &desc);

	if (g_pDeltaBuff != NULL)
	{
		delete [] g_pDeltaBuff;
		g_pDeltaBuff = NULL;
	}
	
	// Allocate a buffer to blit our frames to
	g_pDeltaBuff = new byte[desc.Size];

	memset( g_pDeltaBuff, 0xFF, desc.Size ) ;

	D3DCOLOR			*color_palette;
	


	RECT rectSource;
	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = theHeight-1 ;
	rectSource.right  = theWidth-1 ;

	D3DLOCKED_RECT d3dlr;
	Texture->LockRect(0, &d3dlr, &rectSource, 0);

	m_pitch = d3dlr.Pitch ;

	// Unlock our texture
	Texture->UnlockRect(0);

	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = theHeightHQ-1 ;
	rectSource.right  = theWidthHQ-1 ;

	TextureHQ->LockRect(0, &d3dlr, &rectSource, 0);

	m_pitchHQ = d3dlr.Pitch ;

	// Unlock our texture
	TextureHQ->UnlockRect(0);

	return 0;
}



unsigned long TAB_CONST2[256] = {
   0X0,
   0X77073096,
   0XEE0E612C,
   0X990951BA,
   0X76DC419,
   0X706AF48F,
   0XE963A535,
   0X9E6495A3,
   0XEDB8832,
   0X79DCB8A4,
   0XE0D5E91E,
   0X97D2D988,
   0X9B64C2B,
   0X7EB17CBD,
   0XE7B82D07,
   0X90BF1D91,
   0X1DB71064,
   0X6AB020F2,
   0XF3B97148,
   0X84BE41DE,
   0X1ADAD47D,
   0X6DDDE4EB,
   0XF4D4B551,
   0X83D385C7,
   0X136C9856,
   0X646BA8C0,
   0XFD62F97A,
   0X8A65C9EC,
   0X14015C4F,
   0X63066CD9,
   0XFA0F3D63,
   0X8D080DF5,
   0X3B6E20C8,
   0X4C69105E,
   0XD56041E4,
   0XA2677172,
   0X3C03E4D1,
   0X4B04D447,
   0XD20D85FD,
   0XA50AB56B,
   0X35B5A8FA,
   0X42B2986C,
   0XDBBBC9D6,
   0XACBCF940,
   0X32D86CE3,
   0X45DF5C75,
   0XDCD60DCF,
   0XABD13D59,
   0X26D930AC,
   0X51DE003A,
   0XC8D75180,
   0XBFD06116,
   0X21B4F4B5,
   0X56B3C423,
   0XCFBA9599,
   0XB8BDA50F,
   0X2802B89E,
   0X5F058808,
   0XC60CD9B2,
   0XB10BE924,
   0X2F6F7C87,
   0X58684C11,
   0XC1611DAB,
   0XB6662D3D,
   0X76DC4190,
   0X1DB7106,
   0X98D220BC,
   0XEFD5102A,
   0X71B18589,
   0X6B6B51F,
   0X9FBFE4A5,
   0XE8B8D433,
   0X7807C9A2,
   0XF00F934,
   0X9609A88E,
   0XE10E9818,
   0X7F6A0DBB,
   0X86D3D2D,
   0X91646C97,
   0XE6635C01,
   0X6B6B51F4,
   0X1C6C6162,
   0X856530D8,
   0XF262004E,
   0X6C0695ED,
   0X1B01A57B,
   0X8208F4C1,
   0XF50FC457,
   0X65B0D9C6,
   0X12B7E950,
   0X8BBEB8EA,
   0XFCB9887C,
   0X62DD1DDF,
   0X15DA2D49,
   0X8CD37CF3,
   0XFBD44C65,
   0X4DB26158,
   0X3AB551CE,
   0XA3BC0074,
   0XD4BB30E2,
   0X4ADFA541,
   0X3DD895D7,
   0XA4D1C46D,
   0XD3D6F4FB,
   0X4369E96A,
   0X346ED9FC,
   0XAD678846,
   0XDA60B8D0,
   0X44042D73,
   0X33031DE5,
   0XAA0A4C5F,
   0XDD0D7CC9,
   0X5005713C,
   0X270241AA,
   0XBE0B1010,
   0XC90C2086,
   0X5768B525,
   0X206F85B3,
   0XB966D409,
   0XCE61E49F,
   0X5EDEF90E,
   0X29D9C998,
   0XB0D09822,
   0XC7D7A8B4,
   0X59B33D17,
   0X2EB40D81,
   0XB7BD5C3B,
   0XC0BA6CAD,
   0XEDB88320,
   0X9ABFB3B6,
   0X3B6E20C,
   0X74B1D29A,
   0XEAD54739,
   0X9DD277AF,
   0X4DB2615,
   0X73DC1683,
   0XE3630B12,
   0X94643B84,
   0XD6D6A3E,
   0X7A6A5AA8,
   0XE40ECF0B,
   0X9309FF9D,
   0XA00AE27,
   0X7D079EB1,
   0XF00F9344,
   0X8708A3D2,
   0X1E01F268,
   0X6906C2FE,
   0XF762575D,
   0X806567CB,
   0X196C3671,
   0X6E6B06E7,
   0XFED41B76,
   0X89D32BE0,
   0X10DA7A5A,
   0X67DD4ACC,
   0XF9B9DF6F,
   0X8EBEEFF9,
   0X17B7BE43,
   0X60B08ED5,
   0XD6D6A3E8,
   0XA1D1937E,
   0X38D8C2C4,
   0X4FDFF252,
   0XD1BB67F1,
   0XA6BC5767,
   0X3FB506DD,
   0X48B2364B,
   0XD80D2BDA,
   0XAF0A1B4C,
   0X36034AF6,
   0X41047A60,
   0XDF60EFC3,
   0XA867DF55,
   0X316E8EEF,
   0X4669BE79,
   0XCB61B38C,
   0XBC66831A,
   0X256FD2A0,
   0X5268E236,
   0XCC0C7795,
   0XBB0B4703,
   0X220216B9,
   0X5505262F,
   0XC5BA3BBE,
   0XB2BD0B28,
   0X2BB45A92,
   0X5CB36A04,
   0XC2D7FFA7,
   0XB5D0CF31,
   0X2CD99E8B,
   0X5BDEAE1D,
   0X9B64C2B0,
   0XEC63F226,
   0X756AA39C,
   0X26D930A,
   0X9C0906A9,
   0XEB0E363F,
   0X72076785,
   0X5005713,
   0X95BF4A82,
   0XE2B87A14,
   0X7BB12BAE,
   0XCB61B38,
   0X92D28E9B,
   0XE5D5BE0D,
   0X7CDCEFB7,
   0XBDBDF21,
   0X86D3D2D4,
   0XF1D4E242,
   0X68DDB3F8,
   0X1FDA836E,
   0X81BE16CD,
   0XF6B9265B,
   0X6FB077E1,
   0X18B74777,
   0X88085AE6,
   0XFF0F6A70,
   0X66063BCA,
   0X11010B5C,
   0X8F659EFF,
   0XF862AE69,
   0X616BFFD3,
   0X166CCF45,
   0XA00AE278,
   0XD70DD2EE,
   0X4E048354,
   0X3903B3C2,
   0XA7672661,
   0XD06016F7,
   0X4969474D,
   0X3E6E77DB,
   0XAED16A4A,
   0XD9D65ADC,
   0X40DF0B66,
   0X37D83BF0,
   0XA9BCAE53,
   0XDEBB9EC5,
   0X47B2CF7F,
   0X30B5FFE9,
   0XBDBDF21C,
   0XCABAC28A,
   0X53B39330,
   0X24B4A3A6,
   0XBAD03605,
   0XCDD70693,
   0X54DE5729,
   0X23D967BF,
   0XB3667A2E,
   0XC4614AB8,
   0X5D681B02,
   0X2A6F2B94,
   0XB40BBE37,
   0XC30C8EA1,
   0X5A05DF1B,
   0X2D02EF8D
};




void CXBoxSample::doCPUFixes()
{
	int menuChoice = 0 ;


	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		swprintf( m_menuText[0], L"Set CPU Fixes" );

		swprintf( m_menuText[1], L"Parasite Eve/Vandal Heart fix" ) ; 
		swprintf( m_menuText[3], L"Disable XA sound processing" ) ; 
		swprintf( m_menuText[5], L"Always enable SIO IRQ" ) ; 
		swprintf( m_menuText[7], L"Black and White movies" ) ; 
		swprintf( m_menuText[9], L"Disable CDDA" ) ; 
		swprintf( m_menuText[11], L"Use CPU interpreter" ) ; 
		swprintf( m_menuText[13], L"Always enable SPU IRQ" ) ; 
		swprintf( m_menuText[15], L"InuYasha Sengoku Battle fix" ) ; 

		swprintf( m_menuText[2], ( m_vandalFix ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[4], ( m_psxfix_Xa ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[6], ( m_psxfix_Sio ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[8], ( m_psxfix_Mdec ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[10], ( m_psxfix_Cdda ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[12], ( m_psxfix_Cpu ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[14], ( m_psxfix_SpuIrq ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[16], ( m_psxfix_VSyncWA ) ? L"On" : L"Off" ) ;

		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 9, 0, &m_pnlBackgroundOther, menuChoice, 1, 300 ) ;
		

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			XBInput_GetInput();
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			m_changedSettings = 1 ;

			switch ( menuChoice )
			{
				case 0 : m_vandalFix = !m_vandalFix ; break ;
				case 1 : m_psxfix_Xa = !m_psxfix_Xa  ; break ;
				case 2 : m_psxfix_Sio = !m_psxfix_Sio  ; break ;
				case 3 : m_psxfix_Mdec = !m_psxfix_Mdec  ; break ;
				case 4 : m_psxfix_Cdda = !m_psxfix_Cdda  ; break ;
				case 5 : m_psxfix_Cpu = !m_psxfix_Cpu  ; break ;
				case 6 : m_psxfix_SpuIrq = !m_psxfix_SpuIrq  ; break ;
				case 7 : m_psxfix_VSyncWA = !m_psxfix_VSyncWA  ; break ;
				default : break ;
			}
		}
	}
}

void CXBoxSample::doGraphicsFixes()
{
	int menuChoice = 0 ;


	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		swprintf( m_menuText[0], L"Set Graphics Fixes" );

		swprintf( m_menuText[1], L"Odd/even bit hack" ) ; 
		swprintf( m_menuText[3], L"Expand screen width" ) ; 
		swprintf( m_menuText[5], L"Ignore black brightness color" ) ; 
		swprintf( m_menuText[7], L"Disable coord check" ) ; 
		swprintf( m_menuText[9], L"Use low-res fps timer" ) ; 
		swprintf( m_menuText[11], L"Use PC fps calculation" ) ; 
		swprintf( m_menuText[13], L"Lazy screen updates" ) ; 
		swprintf( m_menuText[15], L"Use old frame skipping" ) ; 
		swprintf( m_menuText[17], L"Frameskip" ) ; 
		swprintf( m_menuText[19], L"Framelimit" ) ; 
		swprintf( m_menuText[21], L"Bit Depth" ) ; 

		for ( int i = 0 ; i < 8 ; i++ )
		{
			swprintf( m_menuText[(i*2)+2], ( m_graphicsFixes & ( 1 << i ) ) ? L"On" : L"Off" );
		}

		swprintf( m_menuText[18], ( m_frameskip ) ? L"On" : L"Off" ) ;
		swprintf( m_menuText[20], ( m_framelimit ) ? L"On" : L"Off" ) ; 
		swprintf( m_menuText[22], ( m_bitDepth==16 ) ? L"16" : L"32" ) ; 

		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 12, 0, &m_pnlBackgroundOther, menuChoice, 1, 300 ) ;
		

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			XBInput_GetInput();
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			m_changedSettings = 1 ;

			switch ( menuChoice )
			{
				case 8 : m_frameskip = !m_frameskip ; break ;
				case 9 : m_framelimit = !m_framelimit ; break ;
				case 10 : if ( m_bitDepth == 16 ) m_bitDepth = 16 ; else m_bitDepth = 16 ; break ;
				default : 
					{
						if ( m_graphicsFixes & ( 1 << menuChoice ) )
						{
							m_graphicsFixes &= ~( 1 << menuChoice ) ;
						}
						else
						{
							m_graphicsFixes |= ( 1 << menuChoice ) ;
						}
					}
					break ;
			}
		}
	}
}






void CXBoxSample::emuLaunch( unsigned int gameSelected, unsigned int isFavorite )
{
	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;

	alwaysOff = 0 ;
	missVBlank = 0 ;

	//doCDGame( ) ;

	//m_pd3dDevice->SetVerticalBlankCallback( vblankCallback ) ;

	initConsole( gameSelected, isFavorite ) ;

	if ( g_autoLaunchGame )
	{
		changeMenu( &m_skin.otherMenu, &m_skin.mainMenu ) ;
		//doTransition( &m_pnlBackgroundOther, &m_pnlBackgroundMain, m_skin.fade, 1 ) ;
	}
	else
	{
		changeMenu( &m_skin.otherMenu, &m_skin.gameSelectMenu ) ;
		//doTransition( &m_pnlBackgroundOther, &m_pnlBackgroundSelect, m_skin.fade, 1 ) ;
	}

	if ( !m_bBgmInGame )
	{
		m_mp3player.pause( FALSE ) ;
	}

	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;

}



void CXBoxSample::doConfigureGame( char *settingsname, char *keysname )
{
	int menuChoice ;
	char *countries[] = { "Auto-detect", "Japan", "USA", "Europe", "Other" } ;
	char *tearing[] = {"Auto", "Never (Faster)", "Always (Cleaner)" } ;

	menuChoice = 0 ;

	loadSettings( settingsname ) ;
	loadKeys( keysname ) ;


	while ( 1 )
	{
		pmenuParams = &(m_skin.otherMenu);

	
		swprintf( m_menuText[0], L"Game Configuration" );
		swprintf( m_menuText[1], L"Country : %S", countries[m_countryCode+1] ) ;
		swprintf( m_menuText[2], L"CD Method : %S", m_cdMethod ? "Normal" : "Perfect Synchro"    );
		swprintf( m_menuText[3], L"4-Player Adaptor on Port : %S", multiport==1 ? "1" : ( multiport == 2 ? "2" : "<Disabled>" )  ) ;
		swprintf( m_menuText[4], L"Show CD LEDs : %S", xbox_Show_LED ? "Yes" : "No" );
		swprintf( m_menuText[5], L"Fast Blur Effect : %S", xbox_Fast_Blur ? "Enabled" : "Disabled" ) ;
		swprintf( m_menuText[6], L"Sprite Limit : %S", xbox_Sprite_Over ? "Enabled" : "Disabled" ) ;
		swprintf( m_menuText[7], L"YM2612 Improvement : %S", xbox_YM2612_Improv ? "Enabled" : "Disabled" ) ;
		swprintf( m_menuText[8], L"DAC Improvement : %S", xbox_DAC_Improv ? "Enabled" : "Disabled" ) ;
		swprintf( m_menuText[9], L"PSG Improvement : %S", xbox_PSG_Improv ? "Enabled" : "Disabled" ) ;
		swprintf( m_menuText[10], L"MSH2 32X Speed : %u", xbox_MSH2_Speed ) ;
		swprintf( m_menuText[11], L"SSH2 32X Speed : %u", xbox_SSH2_Speed ) ;
		swprintf( m_menuText[12], L"Fix Screen Tearing : %S", tearing[xbox_force_fixtear&0x03] ) ;
		swprintf( m_menuText[13], L"Configure Controllers"  );
		
		
		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 14, 0, &m_pnlBackgroundOther, menuChoice, 0, 0 ) ;
		

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
	        XBInput_GetInput();
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;
			switch ( menuChoice )
			{
				case 0 : 
				{
					m_countryCode++ ;

					if ( m_countryCode > 3 )
						m_countryCode = -1 ;
					break ;
				}
				case 1 : m_cdMethod = !m_cdMethod ; break ; 
				case 2 : multiport = (multiport+1)%3 ; break ; 
				case 3 : xbox_Show_LED = !xbox_Show_LED ; break ; 
				case 4 : xbox_Fast_Blur = !xbox_Fast_Blur ; break ; 
				case 5 : xbox_Sprite_Over = !xbox_Sprite_Over ; break ; 
				case 6 : xbox_YM2612_Improv = !xbox_YM2612_Improv ; break ; 
				case 7 : xbox_DAC_Improv = !xbox_DAC_Improv ; break ; 
				case 8 : xbox_PSG_Improv = !xbox_PSG_Improv ; break ; 
				case 9 : xbox_MSH2_Speed = getValuePopup( "MSH2 32X Speed", xbox_MSH2_Speed, 0, 100, &m_pnlBackgroundOther ) ; break ;
				case 10 : xbox_SSH2_Speed = getValuePopup( "SSH2 32X Speed", xbox_SSH2_Speed, 0, 100, &m_pnlBackgroundOther ) ; break ;
				case 11 : xbox_force_fixtear = (xbox_force_fixtear+1)%3 ; break ;
				case 12 : doConfigureControllers() ; break ;
				default : break ;
			}
		}


	}

	saveSettings( settingsname ) ;
	saveKeys( keysname ) ;

}




void CXBoxSample::doLoadNewDisk()
{
	WCHAR str[2000];
	swprintf( str, L"GENS for XBOX  B-Abort  Found %u games", numfiles);

	if ( !SegaCD_Started )
	{
		popupMsg( "You are not currently playing a Sega CD game.", &m_pnlBackgroundOther ) ;
		return ;
	}

	unsigned int selectedGame ;

	changeMenu( &m_skin.otherMenu, &m_skin.gameSelectMenu ) ;


	if ( ( selectedGame = doSelectGame( 0, 1 ) ) != 0xFFFFFFFF ) 
	{

					char                filename[500] ;

					nb_max_track = 0 ;

					strcpy((char*)filename, m_szCurrentDir ) ;
					strcat( (char*)filename, (const char*)files[selectedGame].filename ) ;

					if ( m_bUsingSamba )
					{
						m_smb.close( m_smbCdFile ) ;
					}

					m_bUsingSamba = ( strncmp( filename, "SMB:", 4 ) == 0 ) || ( strncmp( filename, "smb:", 4 ) == 0 ) ;

					loaded_cue = 0 ;

					memset( CD_track, 0, sizeof(CD_track) ) ;


					strcpy( g_cuefile, "" ) ;

					if (strstr (strupr(filename), ".CUE"))
					{
						writexbox( "processing cue\r\n" ) ;

						strcpy( g_cuefile, filename ) ;
						loadCueSheet( g_cuefile ) ;
						filename[0] = 0 ;

						for ( int i = 0 ; i < nb_max_track ; i++ )
						{
							if ( CD_track[i].type == 4 )
							{
								strcpy( filename, CD_track[i].filename ) ;
								break ;
							}
						}


						if ( filename[0] != 0 )
						{
							loaded_cue = 1 ;
						}

					}


					char *p;



				if ( m_bUsingSamba )
				{
					char smbfilename[1024] ;
					char *smbp ;
					char tmp_data[3000] ;

					sprintf( smbfilename, "%s%s", m_smbShare, filename+4 ) ;

					while ( smbp = strchr( smbfilename, '\\' ) )
						*smbp = '/' ;

					//sprintfx( "samba:%s\r\n", smbfilename ) ;

					m_smbCdFile = m_smb.open( smbfilename,O_RDONLY|O_BINARY);


					if ( m_smbCdFile <= 0 )
						return ;

					m_smb.lseek(m_smbCdFile,16*2352,SEEK_SET);
					m_smb.read(m_smbCdFile,tmp_data, 2352) ;

					int filesize = m_smb.lseek(m_smbCdFile,0,SEEK_END);


					struct stat fstats ;

					m_smb.fstat( m_smbCdFile, &fstats ) ;

					filesize = fstats.st_size ;
				}







					//writexbox( "init1" ) ;

					strcpy( g_saveprefix, g_savePath ) ;
					strcat( g_saveprefix, "\\" ) ;
					strcat( g_saveprefix, strrchr( filename, '\\' )+1 ) ;
					//sprintf(saveprefix, "%s\\%s", savedir, (const char*)files[idx].filename);
					p = strchr(g_saveprefix, '.');
					if (p) *p = 0;

					strcpy(g_sramfile, g_saveprefix);
					strcat(g_sramfile, ".srm");

					strcpy(g_keysfile, g_saveprefix);
					strcat(g_keysfile, ".key");

					strcpy(g_settingsfile, g_saveprefix);
					strcat(g_settingsfile, ".stg");

					strcpy(g_bramfile, g_saveprefix);
					strcat(g_bramfile, ".brm");

					strcpy(g_chtfile, g_saveprefix);
					strcat(g_chtfile, ".cht");

					sprintf( g_statefile, "%s.sta", g_saveprefix ) ;

					Change_CD( filename ) ;
	}
}




void CXBoxSample::saveSettings( char *filename )
{
	FILE *setfile ;

	m_changedSettings = 0 ;

	setfile = fopen( filename, "wb" ) ;

	if ( !setfile )
		return ;


	fwrite( &m_countryCode, sizeof(int), 1, setfile ) ;
	fwrite( &m_cdMethod, sizeof(int), 1, setfile ) ;
	fwrite( &multiport, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_Fast_Blur, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_Sprite_Over, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_YM2612_Improv, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_DAC_Improv, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_PSG_Improv, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_MSH2_Speed, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_SSH2_Speed, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_Show_LED, sizeof(int), 1, setfile ) ;
	fwrite( &xbox_force_fixtear, sizeof(int), 1, setfile ) ;

	fclose( setfile ) ;

}

int CXBoxSample::loadSettings( char *filename )
{
	FILE *setfile ;

	m_changedSettings = 0 ;

	setfile = fopen( filename, "rb" ) ;

	m_countryCode = -1 ;
	m_cdMethod = 0 ;
	multiport = 0 ;
	xbox_Fast_Blur = 0 ;
	xbox_Sprite_Over = 0 ;
	xbox_YM2612_Improv = 1 ;
	xbox_DAC_Improv = 0 ;
	xbox_PSG_Improv = 0 ;
	xbox_MSH2_Speed = 100 ;
	xbox_SSH2_Speed = 100 ;
	xbox_Show_LED = 0 ;
	xbox_force_fixtear = 0 ;

	if ( !setfile )
	{

		saveSettings( filename ) ;
		return 1 ;
	}


	fread( &m_countryCode, sizeof(int), 1, setfile ) ;
	fread( &m_cdMethod, sizeof(int), 1, setfile ) ;
	fread( &multiport, sizeof(int), 1, setfile ) ;
	fread( &xbox_Fast_Blur, sizeof(int), 1, setfile ) ;
	fread( &xbox_Sprite_Over, sizeof(int), 1, setfile ) ;
	fread( &xbox_YM2612_Improv, sizeof(int), 1, setfile ) ;
	fread( &xbox_DAC_Improv, sizeof(int), 1, setfile ) ;
	fread( &xbox_PSG_Improv, sizeof(int), 1, setfile ) ;
	fread( &xbox_MSH2_Speed, sizeof(int), 1, setfile ) ;
	fread( &xbox_SSH2_Speed, sizeof(int), 1, setfile ) ;
	fread( &xbox_Show_LED, sizeof(int), 1, setfile ) ;
	fread( &xbox_force_fixtear, sizeof(int), 1, setfile) ;

	if ( ( m_countryCode > 3 ) || ( m_countryCode < -1 ) )
	{
		m_countryCode = -1 ;
	}

	fclose( setfile ) ;

	return 0 ;
}





void CXBoxSample::doCDGame( )
{
	int fResult ;
	TOC toc;
	char xmsg[100] ;
	int sectorA, sectorB ;
	int menuChoice = 0 ;
	int  whichCard ;
	int bdone ;
	int country ; 
	int whichCD ;
	int realCD ;
	WCHAR linemsg[200] ;
	int isSelectMenu = 1 ;
	char *countries[] = { "Auto-detect", "USA", "Japan", "Europe", "Other" } ;

	alwaysOff = 0 ;
	missVBlank= 0 ;

	//country = 0 ;
	//whichCD = 0 ;
	realCD = 1 ;
	bdone = 1 ;
	throttle = 0 ;
	m_currentStartSector = 9999999 ;

/*
	while ( !bdone )
	{
		m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
							 0x00000000, 1.0f, 0L );
		RenderGradientBackground( 0xFF000000, 0xFF000000 );

		MenuBar( 32, 16*(6+menuChoice)+3, 600, 19 ) ;


		m_Font.Begin();
		m_Font.DrawText( m_nXOffset+  32, 16*4, 0xffffffff, L"CD Menu" );
		swprintf( linemsg, L"Country : %S", countries[country] ) ;
		m_Font.DrawText( m_nXOffset+  32, 16*6, menuChoice==0 ? 0xff000000 : 0xffffffff, linemsg );
		swprintf( linemsg, L"Play %S as above country in regular CD mode", files[curr].filename ) ;
		m_Font.DrawText( m_nXOffset+  32, 16*7, menuChoice==1 ? 0xff000000 : 0xffffffff, linemsg );
		swprintf( linemsg, L"Play %S as above country in alternate CD mode", files[curr].filename ) ;
		m_Font.DrawText( m_nXOffset+  32, 16*8, menuChoice==2 ? 0xff000000 : 0xffffffff, linemsg );
		m_Font.DrawText( m_nXOffset+  32, 16*9, menuChoice==3 ? 0xff000000 : 0xffffffff, L"Load CD as above country in regular CD mode" );
		m_Font.DrawText( m_nXOffset+  32, 16*10, menuChoice==4 ? 0xff000000 : 0xffffffff, L"Load CD as above country in alternate CD mode" );
		m_Font.DrawText( m_nXOffset+  32, 16*11, menuChoice==5 ? 0xff000000 : 0xffffffff, L"Eject CD Tray (reboots XBox if Gens was not loaded from DVD/CDRW)" );
		m_Font.DrawText( m_nXOffset+  32, 16*12, menuChoice==6 ? 0xff000000 : 0xffffffff, L"Close CD Tray" );
		m_Font.DrawText( m_nXOffset+  32, 16*14, 0xffffffff, L"Press B to go back" );
		m_Font.End();

		
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );

        XBInput_GetInput();
		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
	        XBInput_GetInput();
			return  ;
		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_DOWN )
		{
			menuChoice = (menuChoice+1)%7 ;
		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_UP )
		{
			if ( menuChoice == 0 )
				menuChoice = 6 ;
			else
				menuChoice-- ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			switch ( menuChoice )
			{
				case 0 : country = (country+1)%5 ; break ;
				case 1 :
				{
					if ( files[curr].isDir ) 
						return ; 
					else
					{
						whichCD = 0 ; 
						realCD = 0 ;
						bdone = 1 ;
					}
					break ;
				}
				case 2 :
				{
					if ( files[curr].isDir ) 
						return ; 
					else
					{
						whichCD = 1 ; 
						realCD = 0 ;
						bdone = 1 ;
					}
					break ;
				}
				case 3 :
				{
					whichCD = 0 ; 
					realCD = 1 ;
					bdone = 1 ;
					break ;
				}
				case 4 :
				{
					whichCD = 1 ; 
					realCD = 1 ;
					bdone = 1 ;
					break ;
				}
				case 5 : m_io.EjectTray() ; break ;
				case 6 : m_io.CloseTray() ; break ;
				default : break ;
			}
		}


	}

*/


//use flags to turn off eject thingy - xbox image -> project options
	//    /TestMediaTypes:0x80000007 


	ANSI_STRING filename;
	OBJECT_ATTRIBUTES attributes;
	IO_STATUS_BLOCK status;
	HANDLE hDevice;
	NTSTATUS error;
	DWORD dummy;
	DWORD byteCount ;

	RtlInitAnsiString(&filename, "\\Device\\Cdrom0" );

	InitializeObjectAttributes(&attributes, &filename, OBJ_CASE_INSENSITIVE, NULL);

	if (NT_SUCCESS(error = NtCreateFile(&m_hCdrom, GENERIC_READ |
		SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attributes, &status, NULL, 0,
		FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN,
		FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT)))
	{
	}
	else
	{
		popupMsg( "Could not access CD - aborting", &m_pnlBackgroundSelect ) ;
		return ;
	}



	if ( m_hCdrom == INVALID_HANDLE_VALUE )
	{
		popupMsg( "Could not access CD - aborting", &m_pnlBackgroundSelect ) ;
		return ;
	}

	if ( ! DeviceIoControl(m_hCdrom, IOCTL_CDROM_READ_TOC, NULL, 0,	&toc, sizeof(TOC), &byteCount, NULL ) )
	{
		CloseHandle( m_hCdrom ) ;
		popupMsg( "Could not read TOC from CD - aborting", &m_pnlBackgroundSelect ) ;
		return  ;
	}

	nb_max_track = toc.lastTrack ;
	memset( CD_track, 0, sizeof(CD_track) ) ;




	SCD.TOC.First_Track = toc.firstTrack;
	SCD.TOC.Last_Track = toc.lastTrack;

	unsigned char numTracks = toc.lastTrack - toc.firstTrack + 1;
	TOCTRACK *t;

	for(int i = 0; i < numTracks; i++)
	{
		t = &(toc.tracks[i]);

		SCD.TOC.Tracks[i].Num = t->trackNumber;
		SCD.TOC.Tracks[i].Type = (t->ADR ) & 0x0F ;		// DATA flag
//		SCD.TOC.Tracks[i].Type = (t->ADR & 0x04) >> 2;		// DATA flag

		SCD.TOC.Tracks[i].MSF.M = t->addr[1];
		SCD.TOC.Tracks[i].MSF.S = t->addr[2];
		SCD.TOC.Tracks[i].MSF.F = t->addr[3];

	}

	SCD.TOC.Tracks[numTracks].Num = toc.tracks[numTracks].trackNumber;
	SCD.TOC.Tracks[numTracks].Type = 0;

	SCD.TOC.Tracks[numTracks].MSF.M = toc.tracks[numTracks].addr[1];
	SCD.TOC.Tracks[numTracks].MSF.S = toc.tracks[numTracks].addr[2];
	SCD.TOC.Tracks[numTracks].MSF.F = toc.tracks[numTracks].addr[3];




	for ( int i = toc.firstTrack; i <= toc.lastTrack; i++)
	{
		int val = 	( toc.tracks[i-1].addr[1] * 60 * 75 ) + 
					( toc.tracks[i-1].addr[2] * 75 ) +
					( toc.tracks[i-1].addr[3]  ) ;
		int frms, mins, secs ;

		mins = toc.tracks[i-1].addr[1] ;
		secs = toc.tracks[i-1].addr[2] ;
		frms = toc.tracks[i-1].addr[3] ;

		/*
		if ( secs < 2 )  //account for standard gap that seems to appear on all cue sheets
		{
			secs = 60 - secs ;
			mins-- ;
		}
		else
		{
			secs -= 2 ;
		}
*/

		CD_track[i].beg_min = mins ;
		CD_track[i].beg_sec = secs ;
		CD_track[i].beg_fra = frms ;
		CD_track[i].type = (((TOCTRACK)(toc.tracks[i-1])).ADR ) & 0x0F ;
		strcpy( CD_track[i].filename, "D:\\blank" ) ;



		sprintf( xmsg, "track #%u, type=%s, size=%u\r\n", i, CD_track[i].type ? "data" : "audio", val ) ;
		writexbox(xmsg) ;

	}




	for ( int i = 1 ; i <= nb_max_track ; i++ )
	{

		if ( i == nb_max_track )
		{
			sectorB = 73 * CD_SECS * CD_FRAMES ; 
	
			sectorA = ( CD_track[i].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i].beg_sec * CD_FRAMES ) +
					  ( CD_track[i].beg_fra  )  ;
	
			CD_track[i].length = sectorB - sectorA ;
		}
		else
		{
			sectorB = ( CD_track[i+1].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i+1].beg_sec * CD_FRAMES ) +
					  ( CD_track[i+1].beg_fra  )  ;
	
			sectorA = ( CD_track[i].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i].beg_sec * CD_FRAMES ) +
					  ( CD_track[i].beg_fra  )  ;
	
			CD_track[i].length = sectorB - sectorA ;
		}

	}



	unsigned char tmp_data[2048*2] ;
	unsigned int CRC ;

	CRC = -1 ;

	sectorA = ( CD_track[1].beg_min * CD_SECS * CD_FRAMES ) +
			  ( CD_track[1].beg_sec * CD_FRAMES ) +
			  ( CD_track[1].beg_fra  )  ;

	m_io.ReadSector( m_hCdrom, sectorA+1, (LPSTR)tmp_data ) ;

	for (int index = 0; index < 2048; index++)
	{
		tmp_data[index] ^= CRC;
		CRC >>= 8;
		CRC ^= TAB_CONST2[tmp_data[index]];
	}
	CRC = ~CRC;


	
	m_state = IN_GAME ;

	

	





	char cd_filename[500] ;

	global_error_message[0] = 0 ;

	m_droppedFrames = 0 ;


//	sleepamount = 0 ;
	throttle = 0 ;
//	blittermode = 1 ;

	memset( m_memMatches, 1, CONSOLE_MEMORY_SIZE ) ;
	m_currentMemMatches = CONSOLE_MEMORY_SIZE ;
	m_numCheats = 0 ;

	nb_max_track = 0 ;


	sprintf( cd_filename, "D:\\SGENROMS\\%02.2X%02.2X%02.2X%02.2X.IMG", (CRC>>24)&0xFF, (CRC>>16)&0xFF, (CRC>>8)&0xFF, CRC&0xFF ) ;

	//strcpy((char*)filename, "D:\\sgenroms\\" ) ;
	//strcpy((char*)cd_filename, m_szCurrentDir ) ;
	//wcsrtombs( (char*)gfilename, (const wchar_t**)(&(files[idx].name)), 100, NULL ) ;
	//strcat( (char*)cd_filename, (const char*)files[idx].filename ) ;


	loaded_cue = 0 ;


	char *p;


	//writexbox( "init1" ) ;

	strcpy( g_saveprefix, g_savePath ) ;
	strcat( g_saveprefix, "\\" ) ;
	strcat( g_saveprefix, strrchr( cd_filename, '\\' )+1 ) ;
	//sprintf(saveprefix, "%s\\%s", savedir, (const char*)files[idx].filename);
	p = strchr(g_saveprefix, '.');
	if (p) *p = 0;

	strcpy(g_sramfile, g_saveprefix);
	strcat(g_sramfile, ".srm");

	strcpy(g_keysfile, g_saveprefix);
	strcat(g_keysfile, ".key");

	strcpy(g_settingsfile, g_saveprefix);
	strcat(g_settingsfile, ".stg");

	strcpy(g_bramfile, g_saveprefix);
	strcat(g_bramfile, ".brm");

	strcpy(g_chtfile, g_saveprefix);
	strcat(g_chtfile, ".cht");

	sprintf( g_statefile, "%s.sta", g_saveprefix ) ;

	changeMenu( &m_skin.mainMenu, &m_skin.otherMenu ) ;
	doConfigureGame( g_settingsfile, g_keysfile ) ;
	isSelectMenu = 0 ;

	if ( m_bNetplay )
	{
		if ( setupNetplay() )
			return ;
	}

	if ( g_autoLaunchGame )
	{
		m_pnlSplashGame.Render() ;
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
	}
	else
	{
		if ( isSelectMenu )
		{
			doTransition( &m_pnlBackgroundMain, &m_pnlSplashGame, m_skin.fade, 1 ) ;
		}
		else
		{
			doTransition( &m_pnlBackgroundOther, &m_pnlSplashGame, m_skin.fade, 1 ) ;
		}
	}
//	nonoise = 0 ;
	
	memset( m_mp3player.m_pSoundBufferData, 0, m_mp3player.stream_buffer_size) ;
	if ( !m_bBgmInGame )
	{
		m_mp3player.pause( TRUE ) ;
	}

	m_sound.init() ;
	m_cdda.init() ;
	//m_mp3player.init() ;

	//writexbox( "init1" ) ;
	cht_load() ;
	ggenie_init() ;

	// Create our texture
	init_texture();


	// Create our sprite driver
	if ( Sprite == NULL )
		D3DXCreateSprite(m_pd3dDevice, &Sprite);
	





	m_fAppTime = 0.0f ;

	g_dwStartTime = GetTickCount() ;
	g_dwTimePaused = 0 ;
	m_dwStartPause = 0 ;

	m_steps = 0 ;

	m_sound.pause( FALSE ) ;
	m_cdda.pause( FALSE ) ;

	m_numFrames = 0 ;
	m_startTime = GetTickCount() ;

	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;

	QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev);

	gensmain(cd_filename,m_countryCode,m_cdMethod,1,0,0, xbox_Fast_Blur,
			xbox_Sprite_Over,
			xbox_YM2612_Improv,
			xbox_DAC_Improv,
			xbox_PSG_Improv,
			xbox_MSH2_Speed,
			xbox_SSH2_Speed,
			xbox_Show_LED
			) ;


	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;

	m_state=MAIN_MENU ;
	saveKeys( g_keysfile ) ;
	saveSettings( g_settingsfile ) ;

	cleanupConsole() ;






	//last thing after finishing game
	CloseHandle( m_hCdrom ) ;
	m_hCdrom = INVALID_HANDLE_VALUE ;






	


}








void CXBoxSample::ggenie_init()
{

	for( int ii = 0; ii < 256; ii++)
	{
		Liste_GG[ii].code[0] = 0;
		Liste_GG[ii].name[0] = 0;
		Liste_GG[ii].active = 0;
		Liste_GG[ii].addr = 0xFFFFFFFF;
		Liste_GG[ii].data = 0;
		Liste_GG[ii].restore = 0xFFFFFFFF;
	}


	int i = 0 ;


	for( int j = 0; j < m_numCheats; j++)
	{
		if ( m_cheatCodes[j].type == 0x97 )
		{

			Liste_GG[i].addr = 0 ;
			Liste_GG[i].data = 0 ;
			strcpy( Liste_GG[i].code, m_cheatCodes[j].code ) ;

			genie_decode(Liste_GG[i].code, (patch *) (&(Liste_GG[i].addr)));
			Liste_GG[i].active = m_cheatCodes[j].enabled ;

			if ( Liste_GG[i].addr != 0xFFFFFFFF )
				i++ ;

		}
	}



}






int CXBoxSample::addEmuSpecificOptions( int start )
{
		swprintf( m_menuText[start], L"Load new disc image");

		return start+1 ;

}

void CXBoxSample::saveGameSpecificSettings( )
{
	saveKeys( g_keysfile ) ;
	saveSettings( g_settingsfile ) ;

}

void CXBoxSample::performEmuSpecificOption( int start, int menuChoice ) 
{
	if ( menuChoice == start )
	{
		doLoadNewDisk() ;
	}
}

int charToHex( char c )
{
	if ( ( c >= '0' ) && ( c <= '9' ) )
		return c-'0' ;
	else
		return c-'A'+10 ;
}

int strToHex( char *str, int len )
{
	int base ;
	int val ;

	base = 1 ;

	val = 0 ;

	for ( int i = len-1 ; i >= 0 ; i-- )
	{
		val += charToHex(str[i])*base ;
		base *= 16 ;
	}

	return val ;
}

int CXBoxSample::validateCode( char *code, CHEAT_CODE *ccode, int codetype )
{
	ccode->type = strToHex( code, 2 ) ;
	ccode->adr = strToHex( code+2, 6 ) ;
	ccode->val = strToHex( code+8, 4 ) ;


	sprintf( ccode->code, "%02.2X%06.6X %04.4X", ccode->type, ccode->adr, ccode->val & 0xFFFF ) ;

	if ( ( ccode->adr >= CONSOLE_MEMORY_SIZE ) )
	{
		return 0 ;
	}
	else if ( ! ( ( ccode->type == 0x80 ) || ( ccode->type == 0x30 ) || ( ccode->type == 0xD0 ) || ( ccode->type == 0xD1 ) || 
				        ( ccode->type == 0xD2 ) || ( ccode->type == 0xD3 ) || ( ccode->type == 0xE0 ) || ( ccode->type == 0xE1 ) || 
				        ( ccode->type == 0xE2 ) || ( ccode->type == 0xE3 ) || ( ccode->type == 0x10 ) || ( ccode->type == 0x11 ) || 
				        ( ccode->type == 0x20 ) || ( ccode->type == 0x21 ) ) )
	{
		return 0 ;
	}

	return 1 ;
}





void CXBoxSample::doSelectMemcards()
{

	int menuChoice = 0 ;


	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		swprintf( m_menuText[0], L"Set Memory Card Slots" );
		swprintf( m_menuText[1], L"Memory Card 1" );
		swprintf( m_menuText[2], L"%u", m_memcardnum1 );
		swprintf( m_menuText[3], L"Memory Card 2" );
		swprintf( m_menuText[4], L"%u", m_memcardnum2 );

		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 3, 0, &m_pnlBackgroundOther, menuChoice, 1, 200 ) ;
		

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			XBInput_GetInput();
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			if ( menuChoice == 0 )
			{
				m_memcardnum1 = getValuePopup( "Memory Card Slot 1", m_memcardnum1, 0, 9, &m_pnlBackgroundOther ) ; 
			}
			else
			{
				m_memcardnum2 = getValuePopup( "Memory Card Slot 2", m_memcardnum2, 0, 9, &m_pnlBackgroundOther ) ; 
			}
		}

	}
}




//-----------------------------------------------------------------------------
// Name: FrameMove
// Desc: Performs per-frame updates
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::FrameMove()
{

	InitializeWithScreen() ;

    return S_OK;
}



void hq3x(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode ) 
{


	unsigned int dstpitchDiff ;
	unsigned int srcpitchDiff ;

	dstpitchDiff = dstPitch - ( ( ( width ) <<2 ) *3);
	srcpitchDiff = srcPitch - ( width << 1 ) ;

	hq3x_32( srcPtr, dstPtr, width, height, dstPitch, dstpitchDiff, srcpitchDiff );

/*
        unsigned short * pTemp16 = (unsigned short *)srcPtr;
        unsigned int   * pTemp32 = (unsigned int *)g_app->g_pBlitBuff;
        unsigned short rgb;
		unsigned int pitchdiffSrc ;
		unsigned int pitchdiffDest ;

		pitchdiffSrc = ( srcPitch - width*2 ) >> 1 ;
		pitchdiffDest = ( g_app->m_pitchHQ - width*4 ) >> 2 ;

		for ( int y = 0 ; y < height ; y++ )
		{
			for ( int x = 0 ; x < width ; x++ )
			{
				rgb = *(pTemp16++);
				*(pTemp32++) = ((rgb & 0xF800) << 8) + ((rgb & 0x07E0) << 5) + ((rgb & 0x001F) << 3);
			}

			pTemp16 += pitchdiffSrc ;
			pTemp32 += pitchdiffDest ;
		}
*/
}

int CXBoxSample::render_to_texture()
{

	//DOXXX
	RECT src, dst;
	byte *curr1, *curr2 ;
	int Dep ;
	
	// Get a description of our level 0 texture so we can figure
	// out the pitch of the texture
	D3DSURFACE_DESC desc;
    Texture->GetLevelDesc(0, &desc);
	
	if ((VDP_Reg.Set4 & 0x1) )
	{
		//width = 320 ;
		Dep = 0;
	}
	else
	{
		//width = 256
		Dep = 64;
	}
	
	//sprintfx( "render w=%u\r\n", w ) ;

	// Allocate a buffer to blit our frames to

	if ( m_xboxSFilter == HQFILTERNUM )
	{
		// Figure out how big of a rect to lock in our texture
		RECT rectSource;
		rectSource.top = 0;
		rectSource.left = 0;
		//rectSource.bottom = (VDP_Num_Vis_Lines<<BLITTERS[blittermode].multiplier)  - 1 ;
		//rectSource.right  = ((320-Dep) << BLITTERS[blittermode].multiplier ) - 1 ;
		rectSource.bottom = theHeightHQ - 1 ;
		rectSource.right  = theWidthHQ  - 1;

		// Lock the rect in our texture
		D3DLOCKED_RECT d3dlr;
		TextureHQ->LockRect(0, &d3dlr, &rectSource, 0);



		float mx, my ;

		int spitch ;

		spitch = ( ((320-Dep)*2) + ( 32 + Dep*2)   ) ;

		SOFTWARE_FILTERS[m_xboxSFilter].blitfunc( ((unsigned char*)MD_Screen)+16+spitch, spitch, g_pDeltaBuff+spitch, (unsigned char*)d3dlr.pBits, m_pitchHQ, 320-Dep, VDP_Num_Vis_Lines, 0 ) ;
		//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
		//SOFTWARE_FILTERS[m_xboxSFilter].blitfunc( ((unsigned char*)MD_Screen)+16+spitch, spitch, g_pDeltaBuff+spitch, g_pAlignBuff, m_pitch, 320-Dep, VDP_Num_Vis_Lines, 0 ) ;
		//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
		TextureHQ->UnlockRect(0);

		g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, D3DCOLOR_XRGB(0,0,0), 0.0f, 0L);
		//g_pd3dDevice->BeginScene();

		//memcpy( g_pDeltaBuff, ((unsigned char*)MD_Screen)+16, spitch*VDP_Num_Vis_Lines ) ;
		mx = (float)m_nScreenMaxX / (((float)(320-Dep))*3.0f) ;
		my = (float)m_nScreenMaxY / ((float)VDP_Num_Vis_Lines*3.0f);

		m_gameRectSource.top = 0;
		m_gameRectSource.left = 0;
		m_gameRectSource.bottom = (VDP_Num_Vis_Lines - 1)*3 ;
		m_gameRectSource.right  = ((320-Dep) - 1)*3;


		m_gameVecScale.x = mx ; m_gameVecScale.y = my;
		m_gameVecTranslate.x = m_nScreenX ; m_gameVecTranslate.y = m_nScreenY ;
		D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0);

		m_pnlGameScreenHQ.Render(0,0,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;
	}
	else
	{
		// Figure out how big of a rect to lock in our texture
		RECT rectSource;
		rectSource.top = 0;
		rectSource.left = 0;
		//rectSource.bottom = (VDP_Num_Vis_Lines<<BLITTERS[blittermode].multiplier)  - 1 ;
		//rectSource.right  = ((320-Dep) << BLITTERS[blittermode].multiplier ) - 1 ;
		rectSource.bottom = theHeight - 1 ;
		rectSource.right  = theWidth  - 1;

		m_bOKToDraw = 0 ;

		// Lock the rect in our texture
		D3DLOCKED_RECT d3dlr;
		Texture->LockRect(0, &d3dlr, &rectSource, 0);



		float mx, my ;

		if ( m_xboxSFilter )
		{
			int spitch ;

			spitch = ( ((320-Dep)*2) + ( 32 + Dep*2)   ) ;

			SOFTWARE_FILTERS[m_xboxSFilter].blitfunc( ((unsigned char*)MD_Screen)+16+spitch, spitch, g_pDeltaBuff+spitch, (unsigned char*)d3dlr.pBits, m_pitch, 320-Dep, VDP_Num_Vis_Lines, 0 ) ;
			//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
			//SOFTWARE_FILTERS[m_xboxSFilter].blitfunc( ((unsigned char*)MD_Screen)+16+spitch, spitch, g_pDeltaBuff+spitch, g_pAlignBuff, m_pitch, 320-Dep, VDP_Num_Vis_Lines, 0 ) ;
			//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
			Texture->UnlockRect(0);
			m_bOKToDraw = 1 ;

			g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, D3DCOLOR_XRGB(0,0,0), 0.0f, 0L);
			//g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 0.0f, 0L);
			//g_pd3dDevice->BeginScene();

			//memcpy( g_pDeltaBuff, ((unsigned char*)MD_Screen)+16, spitch*VDP_Num_Vis_Lines ) ;
			mx = (float)m_nScreenMaxX / (((float)(320-Dep))*2.0f) ;
			my = (float)m_nScreenMaxY / ((float)VDP_Num_Vis_Lines*2.0f);

			m_gameRectSource.top = 0;
			m_gameRectSource.left = 0;
			m_gameRectSource.bottom = (VDP_Num_Vis_Lines - 1)*2 ;
			m_gameRectSource.right  = ((320-Dep) - 1)*2;
		}
		else
		{
			Blit_X1_MMX( (unsigned char*)d3dlr.pBits, d3dlr.Pitch, 320-Dep, VDP_Num_Vis_Lines, 32 + Dep * 2 ) ;
			//XGSwizzleRect(g_pBlitBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
			//Blit_X1_MMX( g_pBlitBuff, d3dlr.Pitch, 320-Dep, VDP_Num_Vis_Lines, 32 + Dep * 2 ) ;
			//XGSwizzleRect(g_pBlitBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
			Texture->UnlockRect(0);
			m_bOKToDraw = 1 ;
			
			//g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 0.0f, 0L);
			g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, D3DCOLOR_XRGB(0,0,0), 0.0f, 0L);
			//g_pd3dDevice->BeginScene();

			mx = (float)m_nScreenMaxX / ((float)320-Dep) ;
			my = (float)m_nScreenMaxY / ((float)VDP_Num_Vis_Lines);

			m_gameRectSource.top = 0;
			m_gameRectSource.left = 0;
			m_gameRectSource.bottom = (VDP_Num_Vis_Lines - 1) ;
			m_gameRectSource.right  = ((320-Dep) - 1);
		}



		m_gameVecScale.x = mx ; m_gameVecScale.y = my;
		m_gameVecTranslate.x = m_nScreenX ; m_gameVecTranslate.y = m_nScreenY ;
		D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0);

		m_pnlGameScreen.Render(0,0,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;
	}
	//m_numFrames++ ;

	if ( global_error_message[0] )
	{
		WCHAR msg[500] ;
		m_msgDelay-- ;
		swprintf( msg, L"%S", global_error_message ) ;

		m_Font.DrawText( 48, 48, 0xFFFFFFFF, msg, 0x00000000, 1, 0, 640, 480, pmenuParams->size   ) ;

		if ( m_msgDelay <= 0 )
		{
			global_error_message[0] = 0 ;
		}
	}
	/*
	else
	{
		if ( GetTickCount() - m_startTime > 0 )
		{
			sprintf( global_error_message, "%2.2f FPS - %u frames in %3.2f sec", ((float)m_numFrames*1000.0f)/((float)( GetTickCount() - m_startTime )), m_numFrames, ((float)( GetTickCount() - m_startTime ))/1000.0f ) ;
			m_msgDelay = 1 ;
			WCHAR msg[500] ;
			swprintf( msg, L"%S", global_error_message ) ;

			m_Font.DrawText( 48, 48, 0xFFFFFFFF, msg, 0x00000000, 1, 0, 640, 480, pmenuParams->size   ) ;
		}
		else
		{
			sprintf( global_error_message, "<inf> FPS" ) ;
			m_msgDelay = 1 ;
			WCHAR msg[500] ;
			swprintf( msg, L"%S", global_error_message ) ;

			m_Font.DrawText( 48, 48, 0xFFFFFFFF, msg, 0x00000000, 1, 0, 640, 480, pmenuParams->size   ) ;
		}
	}
*/
	// End the scene.
	//g_pd3dDevice->EndScene();


	desiredFPS = ( CPU_Mode ? 50.0f : 60.0f ) ;

	if ( throttle )
	{
		desiredFPS = desiredFPS * 3.0f ;
		alwaysOff = 0 ;
		missVBlank = 0 ;
		m_numFrames = 1 ;
	}

	sounddanger = ( sounddanger || ( FPS < (desiredFPS-2.0f) ) );


	if ( ( _32X_Started ) && ( m_numFrames > 180 ) && ( ((float)missVBlank/(float)m_numFrames) > 0.2f ) )
	{
		alwaysOff = 1 ;
	}

	if ( xbox_force_fixtear == 1 )
	{
		alwaysOff = 1 ;
	}
	else if ( xbox_force_fixtear == 2 )
	{
		alwaysOff = 0 ;
	}

	if ( ( !throttle ) && ( !sounddanger ) && ( !alwaysOff ) )
		g_pd3dDevice->BlockUntilVerticalBlank() ;
	else
	{
		missVBlank++ ;
	}

	g_pd3dDevice->Present(NULL, NULL, NULL, NULL);




	do
	{
		QueryPerformanceCounter((union _LARGE_INTEGER *) m_performanceCurr);

		if (m_performanceCurr[0] != m_performancePrev[0])
		{					
			FPS = (float) (m_performanceFreq[0])  / (float) (m_performanceCurr[0] - m_performancePrev[0]);
			sprintf( global_error_message, "fps=%.1f off=%u\r\n", FPS, alwaysOff);
		}
		else
		{
			FPS = 100.0f ;
			//sprintf( global_error_message, "fps=too much...\r\n");
		}

		//view_fps = 0;
	} while ( FPS > desiredFPS ) ;

	m_performancePrev[0] = m_performanceCurr[0];


	return 1;
}

void CXBoxSample::InitializeEmuSpecific()
{
	m_changedSettings = 0 ;

	m_cdda.dsound = m_sound.dsound ;
	m_cdda.dsound_init() ;
	m_cdda.m_fps = m_d3dpp.FullScreen_RefreshRateInHz ;
	g_cdda = &m_cdda ;

	for ( int i = 0 ; i < 99 ; i++ )
	{
		if ( ! m_relaxTracks[i].Initialize( m_rlxShare ) )
		{
			//sprintfx( "no init main relax\r\n") ;
		}
	}

	m_cdDataBuffer = (unsigned char*)malloc( CD_DATA_BUFFER_SIZE ) ;


}


//-----------------------------------------------------------------------------
// Name: Render
// Desc: Renders the scene
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::Render()
{



    return S_OK;
}


void CXBoxSample::doEmulatorOptions()
{
	int menuChoice = 0 ;


	return ; 

	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		swprintf( m_menuText[0], L"Emulator Specific Options" );
		swprintf( m_menuText[1], L"Set Memory Card Slot");
		swprintf( m_menuText[2], L"Set Graphics Fixes");
		swprintf( m_menuText[3], L"Set CPU Fixes");
		
		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 4, 0, &m_pnlBackgroundOther, menuChoice, 0, 0 ) ;
		

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			XBInput_GetInput();
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;
			switch ( menuChoice )
			{
				case 0 : doSelectMemcards() ; break ;
				case 1 : doGraphicsFixes() ; break ;
				case 2 : doCPUFixes() ; break ;
				default : break ;
			}
		}


	}

}





int CXBoxSample::addGameGenieCode()
{

	m_changedGenie =1 ;
	
	CHEAT_CODE code ;

	code.adr = 0 ;
	code.val = 0 ;
	code.enabled = 0 ;
	code.desc[0] = 0 ;
	memset( code.code, 0, sizeof(code.code) ) ;
	strcpy( code.code, "AAAAAAAA" ) ;

	code.type = 0x97 ;

	m_cheatCodes = (CHEAT_CODE*)realloc( m_cheatCodes, sizeof(CHEAT_CODE) * ( m_numCheats  + 1 ) ) ;

	memcpy( &(m_cheatCodes[m_numCheats]),&code, sizeof(CHEAT_CODE) ) ;
	m_numCheats++ ;

	return 0 ;
	
	
}


void CXBoxSample::doEditGameGenie( int selected )
{
	char szNewDir[MAX_PATH] ;
	DWORD color ;
	int numpositions ;
	CHEAT_CODE editedCode ;
	FILE *outfile ;
	int numpad ;
	int pos ;
	int panelx, panely ;
	CPanel panel ;
	LPDIRECT3DTEXTURE8	panelTexture ;
	int charspacing ;
	char truncCode[30] ;
	WCHAR msg[50] ;
	WCHAR *lines[100] = { L"L/R Trigger - Change Position", 
							L"A - Select Digit",
							L"START - Save Code",
							L"B - Cancel" } ;
	int posx[4] ;



	if ( selected == -1 )
	{
		return ;
	}

	m_changedGenie =1 ;

	for ( int i = 0 ; i < 4 ; i++ )
	{
		posx[i] = (640-m_Font.GetWidth( lines[i] )) / 2 ;
	}


	numpad = 0 ;
	pos = 0 ;

	outfile = fopen( "X:\\NUMPADG.PNG", "wb" ) ;
	if ( outfile == NULL )
		return ;

	fwrite( NUMPAD_GENIE_SEGA, sizeof(char), sizeof(NUMPAD_GENIE_SEGA), outfile ) ;
	fclose( outfile ) ;



	pmenuParams = &(m_skin.otherMenu) ;
	
	if (D3DXCreateTextureFromFileEx(m_pd3dDevice, "X:\\NUMPADG.PNG",
		 NUMPAD_GENIE_SEGA_WIDTH, NUMPAD_GENIE_SEGA_HEIGHT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED,
		 //D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED,
		 D3DX_FILTER_NONE , D3DX_FILTER_NONE, 0, NULL, NULL, &panelTexture )==D3D_OK)
	{
		if ( FAILED(panel.Create(m_pd3dDevice, panelTexture , FALSE, NUMPAD_GENIE_SEGA_WIDTH, NUMPAD_GENIE_SEGA_HEIGHT)) )
		{
			panelTexture->Release() ;
			return  ;
		}
	}
	else
	{
		return  ;
	}
	
	charspacing = 0 ;

	for ( int i = 0 ; i < 10 ; i++ )
	{
		swprintf( msg, L"%c", '0' + i ) ;
		if ( m_Font.GetWidth( msg ) > charspacing )
			charspacing = m_Font.GetWidth( msg ) ;
	}
	for ( int i = 0 ; i < 6 ; i++ )
	{
		swprintf( msg, L"%c", 'A' + i ) ;
		if ( m_Font.GetWidth( msg ) > charspacing )
			charspacing = m_Font.GetWidth( msg ) ;
	}






	truncCode[0] = 0 ;
	int cnt = 0 ;

	numpositions = 8 ;

	for ( int i = 0 ; ( cnt < numpositions ) && ( i<19) ; i++ )
	{
		if ( m_cheatCodes[selected].code[i] != ' ' ) 
		{
			truncCode[cnt] = m_cheatCodes[selected].code[i] ;
			cnt++ ;
		}
	}

	truncCode[cnt] = 0 ;

	charspacing += 5 ;
	
	LPDIRECT3DTEXTURE8	colorSquareTexture;

	D3DXCreateTexture(m_pd3dDevice, 1, 1, 0, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &colorSquareTexture);
	
	D3DSURFACE_DESC desc;
    colorSquareTexture->GetLevelDesc(0, &desc);


	RECT rectSource;
	D3DLOCKED_RECT d3dlr;


	if ( MenuSprite==NULL )
		D3DXCreateSprite(m_pd3dDevice, &MenuSprite);
	if ( Sprite==NULL )
		D3DXCreateSprite(m_pd3dDevice, &Sprite);


	color = 0x800066CC ;

	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = 0;
	rectSource.right  = 0 ;

	colorSquareTexture->LockRect(0, &d3dlr, &rectSource, 0);

	memcpy( d3dlr.pBits, &color, sizeof(color) ) ;

	colorSquareTexture->UnlockRect(0);

	panelx = (640-NUMPAD_GENIE_SEGA_WIDTH)/2 ;
	panely = 82 ; 

	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
							0x00000000, 0.0f, 0L );
		RenderGradientBackground( 0xFF000000, 0xFF000000 );

		D3DXCOLOR d3color( 1.0, 1.0, 1.0, 0.5 ) ;
		//DWORD holdTrans = pmenuParams->panel->m_colDiffuse ;
		//pmenuParams->panel->SetAlpha( (holdTrans>>24) / 2 ) ;
		pmenuParams->panel->Render( );
		Sprite->Draw(Texture, &m_gameRectSource, &m_gameVecScale, NULL, 0, &m_gameVecTranslate, d3color);
		//pmenuParams->panel->SetAlpha( (holdTrans>>24)  ) ;

		panel.Render( panelx, panely, NUMPAD_GENIE_SEGA_WIDTH, NUMPAD_GENIE_SEGA_HEIGHT) ;


		m_mp3player.process() ;


		D3DXVECTOR2 vecScale( 1, 1 ) ;
		D3DXVECTOR2 vecTranslate( panelx + 4 + ( 53 * ( numpad % 8 )), panely + 4 + ( 53 * ( numpad / 8 ) ) ) ;
		D3DXCOLOR sd3color(1.0, 1.0, 1.0, 1.0);
		rectSource.top = 0;
		rectSource.left = 0;
		rectSource.bottom = 49;
		rectSource.right  = 49 ;

		MenuSprite->Draw(colorSquareTexture, &rectSource, &vecScale, NULL, 0, &vecTranslate, sd3color);

		for ( int i = 0 ; i < numpositions ; i++ )
		{
			swprintf( msg, L"%c", truncCode[i] ) ;
			m_Font.DrawText( ((640-(charspacing*numpositions))/2) + i*charspacing, (panely-pmenuParams->lineHeight)-10, 
				pos==i ? pmenuParams->selectedColor : pmenuParams->normalColor, msg, pmenuParams->selectBarColor, pos==i, 0, 0, 0, 0) ;
		}

		for ( int i = 0 ; i < 4 ; i++ )
		{
			m_Font.DrawText( posx[i], panely+NUMPAD_GENIE_SEGA_HEIGHT+10 + (pmenuParams->lineHeight*i), 
				pmenuParams->normalColor, lines[i], pmenuParams->selectBarColor, 0, 0, 0, 0, 0) ;
		}


		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );

		XBInput_GetInput();
		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			XBInput_GetInput();
			break ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			switch ( numpad )
			{
				case 0 : truncCode[pos] = '0' ; break ; 
				case 1 : truncCode[pos] = '1' ; break ; 
				case 2 : truncCode[pos] = '2' ; break ; 
				case 3 : truncCode[pos] = '3' ; break ; 
				case 4 : truncCode[pos] = '4' ; break ; 
				case 5 : truncCode[pos] = '5' ; break ; 
				case 6 : truncCode[pos] = '6' ; break ; 
				case 7 : truncCode[pos] = '7' ; break ; 
				case 8 : truncCode[pos] = '8' ; break ; 
				case 9 : truncCode[pos] = '9' ; break ; 
				case 10 : truncCode[pos] = 'A' ; break ; 
				case 11 : truncCode[pos] = 'B' ; break ; 
				case 12 : truncCode[pos] = 'C' ; break ; 
				case 13 : truncCode[pos] = 'D' ; break ; 
				case 14 : truncCode[pos] = 'E' ; break ; 
				case 15 : truncCode[pos] = 'F' ; break ; 
				case 16 : truncCode[pos] = 'G' ; break ; 
				case 17 : truncCode[pos] = 'H' ; break ; 
				case 18 : truncCode[pos] = 'J' ; break ; 
				case 19 : truncCode[pos] = 'K' ; break ; 
				case 20 : truncCode[pos] = 'L' ; break ; 
				case 21 : truncCode[pos] = 'M' ; break ; 
				case 22 : truncCode[pos] = 'N' ; break ; 
				case 23 : truncCode[pos] = 'P' ; break ; 
				case 24 : truncCode[pos] = 'R' ; break ; 
				case 25 : truncCode[pos] = 'S' ; break ; 
				case 26 : truncCode[pos] = 'T' ; break ; 
				case 27 : truncCode[pos] = 'V' ; break ; 
				case 28 : truncCode[pos] = 'W' ; break ; 
				case 29 : truncCode[pos] = 'X' ; break ; 
				case 30 : truncCode[pos] = 'Y' ; break ; 
				case 31 : truncCode[pos] = 'Z' ; break ; 
				default : truncCode[pos] = '0' ; break ;
			}

			pos = (pos+1)%numpositions ;
		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_RIGHT )
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			if ( ( numpad % 8 ) == 7 )
				numpad -= 7 ;
			else
				numpad++ ;

		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_LEFT )
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			if ( ( numpad %8 ) == 0 )
				numpad += 7 ;
			else
				numpad-- ;

		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_UP )
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			if ( numpad < 8 )
				numpad += 24 ;
			else
				numpad -= 8 ;

		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_DPAD_DOWN )
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			if ( numpad > 23 )
				numpad -= 24 ;
			else
				numpad += 8 ;

		}
		else if (g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER])
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			pos = (pos+1)%numpositions ;
		}
		else if (g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER])
		{
			m_sfxMenuMove.Play( DSBPLAY_FROMSTART ) ;
			pos = (pos+(numpositions-1))%numpositions ;
		}
		else if ( g_Gamepads[0].hDevice && g_Gamepads[0].wPressedButtons & XINPUT_GAMEPAD_START )
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			memcpy( &editedCode, &(m_cheatCodes[selected]), sizeof(CHEAT_CODE) ) ;
			strcpy( editedCode.code, truncCode ) ;

			struct patch newpatch;

			newpatch.addr = 0 ;
			newpatch.data = 0 ;

			genie_decode( truncCode, &newpatch);

			if ( newpatch.addr != 0xFFFFFFFF ) 
			{
				memcpy( &(m_cheatCodes[selected]), &editedCode, sizeof(CHEAT_CODE) ) ;
				m_cheatCodes[selected].adr = newpatch.addr ;
				m_cheatCodes[selected].val = newpatch.data ;
				break ;
			}
			else
			{
				popupMsg( "The code you entered is invalid.", &m_pnlBackgroundOther ) ;
			}
		}
	}

	panelTexture->Release() ;
	colorSquareTexture->Release() ;

}



void CXBoxSample::updateEmuSpecificCheats( ) 
{
}




/**
  This routine should be called regularly to handle events
*/

int CXBoxSample::handleEvents()
{
    INT32 resistance ;
	float newRes ;
	static int doInsert = 0 ;
	static int doChange = 0 ;

	updateCheats2() ;

	if ( g_app->pollXBoxControllers() )
	{
		m_state = MAIN_MENU ;
		Gens_Running = 0 ;
		return 1;
	}
	
	g_app->checkGeneralEvents() ;	

	if ( g_app->m_bNetplay )
	{
		if ( m_netplayCurr == m_netplaySkip ) //we have read some network data
		{
			if ( g_app->m_bNetplay == 2 )  //server
			{
				g_app->m_emuControllers[1] = g_app->m_networkEmuControllers[0] ;
			}
			else //client
			{
				g_app->m_emuControllers[1] = g_app->m_emuControllers[0] ;
				g_app->m_emuControllers[0] = g_app->m_networkEmuControllers[0] ;
			}
		}
		else //we did not poll network - use last values
		{
			if ( g_app->m_bNetplay == 2 )  //server
			{
				g_app->m_emuControllers[0] = g_app->m_prevEmuControllers[0] ;
				g_app->m_emuControllers[1] = g_app->m_networkEmuControllers[0] ;
			}
			else //client
			{
				g_app->m_emuControllers[1] = g_app->m_prevEmuControllers[0] ;
				g_app->m_emuControllers[0] = g_app->m_networkEmuControllers[0] ;
			}
		}

	}


//	if ( g_Gamepads[0].hDevice )
	{
		Controller_1_A = !(m_emuControllers[0] & JOY_A) ;
		Controller_1_B = !(m_emuControllers[0] & JOY_B) ;
		Controller_1_C = !(m_emuControllers[0] & JOY_C) ;
		Controller_1_X = !(m_emuControllers[0] & JOY_X) ;
		Controller_1_Y = !(m_emuControllers[0] & JOY_Y) ;
		Controller_1_Z = !(m_emuControllers[0] & JOY_Z) ;
		Controller_1_Start = !(m_emuControllers[0] & JOY_START) ;
		Controller_1_Mode = !(m_emuControllers[0] & JOY_MODE) ;
		Controller_1_Up = !(m_emuControllers[0] & JOY_UP) ;
		Controller_1_Down = !(m_emuControllers[0] & JOY_DOWN) ;
		Controller_1_Left = !(m_emuControllers[0] & JOY_LEFT) ;
		Controller_1_Right = !(m_emuControllers[0] & JOY_RIGHT) ;
	}
	/*
	else
	{
		Controller_1_Left = 1 ;
		Controller_1_Right = 1 ;
		Controller_1_Up = 1 ;
		Controller_1_Down = 1 ;
		Controller_1_A = 1 ;
		Controller_1_B = 1 ;
		Controller_1_C = 1 ;
		Controller_1_X = 1 ;
		Controller_1_Y = 1 ;
		Controller_1_Z = 1 ;
		Controller_1_Start = 1 ;
		Controller_1_Mode = 1 ;

	}

	if ( g_Gamepads[1].hDevice )*/
	{

		Controller_2_A = !(m_emuControllers[1] & JOY_A) ;
		Controller_2_B = !(m_emuControllers[1] & JOY_B) ;
		Controller_2_C = !(m_emuControllers[1] & JOY_C) ;
		Controller_2_X = !(m_emuControllers[1] & JOY_X) ;
		Controller_2_Y = !(m_emuControllers[1] & JOY_Y) ;
		Controller_2_Z = !(m_emuControllers[1] & JOY_Z) ;
		Controller_2_Start = !(m_emuControllers[1] & JOY_START) ;
		Controller_2_Mode = !(m_emuControllers[1] & JOY_MODE) ;
		Controller_2_Up = !(m_emuControllers[1] & JOY_UP) ;
		Controller_2_Down = !(m_emuControllers[1] & JOY_DOWN) ;
		Controller_2_Left = !(m_emuControllers[1] & JOY_LEFT) ;
		Controller_2_Right = !(m_emuControllers[1] & JOY_RIGHT) ;


		Controller_1B_A = !(m_emuControllers[1] & JOY_A) ;
		Controller_1B_B = !(m_emuControllers[1] & JOY_B) ;
		Controller_1B_C = !(m_emuControllers[1] & JOY_C) ;
		Controller_1B_X = !(m_emuControllers[1] & JOY_X) ;
		Controller_1B_Y = !(m_emuControllers[1] & JOY_Y) ;
		Controller_1B_Z = !(m_emuControllers[1] & JOY_Z) ;
		Controller_1B_Start = !(m_emuControllers[1] & JOY_START) ;
		Controller_1B_Mode = !(m_emuControllers[1] & JOY_MODE) ;
		Controller_1B_Up = !(m_emuControllers[1] & JOY_UP) ;
		Controller_1B_Down = !(m_emuControllers[1] & JOY_DOWN) ;
		Controller_1B_Left = !(m_emuControllers[1] & JOY_LEFT) ;
		Controller_1B_Right = !(m_emuControllers[1] & JOY_RIGHT) ;


	}
	/*
	else
	{
		Controller_2_Left = 1 ;
		Controller_2_Right = 1 ;
		Controller_2_Up = 1 ;
		Controller_2_Down = 1 ;
		Controller_2_A = 1 ;
		Controller_2_B = 1 ;
		Controller_2_C = 1 ;
		Controller_2_X = 1 ;
		Controller_2_Y = 1 ;
		Controller_2_Z = 1 ;
		Controller_2_Start = 1 ;
		Controller_2_Mode = 1 ;

		Controller_1B_Left = 1 ;
		Controller_1B_Right = 1 ;
		Controller_1B_Up = 1 ;
		Controller_1B_Down = 1 ;
		Controller_1B_A = 1 ;
		Controller_1B_B = 1 ;
		Controller_1B_C = 1 ;
		Controller_1B_X = 1 ;
		Controller_1B_Y = 1 ;
		Controller_1B_Z = 1 ;
		Controller_1B_Start = 1 ;
		Controller_1B_Mode = 1 ;
	}



	if ( g_Gamepads[2].hDevice )*/
	{

	
		Controller_1C_A = !(m_emuControllers[2] & JOY_A) ;
		Controller_1C_B = !(m_emuControllers[2] & JOY_B) ;
		Controller_1C_C = !(m_emuControllers[2] & JOY_C) ;
		Controller_1C_X = !(m_emuControllers[2] & JOY_X) ;
		Controller_1C_Y = !(m_emuControllers[2] & JOY_Y) ;
		Controller_1C_Z = !(m_emuControllers[2] & JOY_Z) ;
		Controller_1C_Start = !(m_emuControllers[2] & JOY_START) ;
		Controller_1C_Mode = !(m_emuControllers[2] & JOY_MODE) ;
		Controller_1C_Up = !(m_emuControllers[2] & JOY_UP) ;
		Controller_1C_Down = !(m_emuControllers[2] & JOY_DOWN) ;
		Controller_1C_Left = !(m_emuControllers[2] & JOY_LEFT) ;
		Controller_1C_Right = !(m_emuControllers[2] & JOY_RIGHT) ;
	  
		Controller_2B_A = !(m_emuControllers[2] & JOY_A) ;
		Controller_2B_B = !(m_emuControllers[2] & JOY_B) ;
		Controller_2B_C = !(m_emuControllers[2] & JOY_C) ;
		Controller_2B_X = !(m_emuControllers[2] & JOY_X) ;
		Controller_2B_Y = !(m_emuControllers[2] & JOY_Y) ;
		Controller_2B_Z = !(m_emuControllers[2] & JOY_Z) ;
		Controller_2B_Start = !(m_emuControllers[2] & JOY_START) ;
		Controller_2B_Mode = !(m_emuControllers[2] & JOY_MODE) ;
		Controller_2B_Up = !(m_emuControllers[2] & JOY_UP) ;
		Controller_2B_Down = !(m_emuControllers[2] & JOY_DOWN) ;
		Controller_2B_Left = !(m_emuControllers[2] & JOY_LEFT) ;
		Controller_2B_Right = !(m_emuControllers[2] & JOY_RIGHT) ;
		

	}
	/*
	else
	{
		Controller_1C_Left = 1 ;
		Controller_1C_Right = 1 ;
		Controller_1C_Up = 1 ;
		Controller_1C_Down = 1 ;
		Controller_1C_A = 1 ;
		Controller_1C_B = 1 ;
		Controller_1C_C = 1 ;
		Controller_1C_X = 1 ;
		Controller_1C_Y = 1 ;
		Controller_1C_Z = 1 ;
		Controller_1C_Start = 1 ;
		Controller_1C_Mode = 1 ;

		Controller_2B_Left = 1 ;
		Controller_2B_Right = 1 ;
		Controller_2B_Up = 1 ;
		Controller_2B_Down = 1 ;
		Controller_2B_A = 1 ;
		Controller_2B_B = 1 ;
		Controller_2B_C = 1 ;
		Controller_2B_X = 1 ;
		Controller_2B_Y = 1 ;
		Controller_2B_Z = 1 ;
		Controller_2B_Start = 1 ;
		Controller_2B_Mode = 1 ;
	
	
	}

	if ( g_Gamepads[3].hDevice )*/
	{

		Controller_1D_A = !(m_emuControllers[3] & JOY_A) ;
		Controller_1D_B = !(m_emuControllers[3] & JOY_B) ;
		Controller_1D_C = !(m_emuControllers[3] & JOY_C) ;
		Controller_1D_X = !(m_emuControllers[3] & JOY_X) ;
		Controller_1D_Y = !(m_emuControllers[3] & JOY_Y) ;
		Controller_1D_Z = !(m_emuControllers[3] & JOY_Z) ;
		Controller_1D_Start = !(m_emuControllers[3] & JOY_START) ;
		Controller_1D_Mode = !(m_emuControllers[3] & JOY_MODE) ;
		Controller_1D_Up = !(m_emuControllers[3] & JOY_UP) ;
		Controller_1D_Down = !(m_emuControllers[3] & JOY_DOWN) ;
		Controller_1D_Left = !(m_emuControllers[3] & JOY_LEFT) ;
		Controller_1D_Right = !(m_emuControllers[3] & JOY_RIGHT) ;

	
		Controller_2C_A = !(m_emuControllers[3] & JOY_A) ;
		Controller_2C_B = !(m_emuControllers[3] & JOY_B) ;
		Controller_2C_C = !(m_emuControllers[3] & JOY_C) ;
		Controller_2C_X = !(m_emuControllers[3] & JOY_X) ;
		Controller_2C_Y = !(m_emuControllers[3] & JOY_Y) ;
		Controller_2C_Z = !(m_emuControllers[3] & JOY_Z) ;
		Controller_2C_Start = !(m_emuControllers[3] & JOY_START) ;
		Controller_2C_Mode = !(m_emuControllers[3] & JOY_MODE) ;
		Controller_2C_Up = !(m_emuControllers[3] & JOY_UP) ;
		Controller_2C_Down = !(m_emuControllers[3] & JOY_DOWN) ;
		Controller_2C_Left = !(m_emuControllers[3] & JOY_LEFT) ;
		Controller_2C_Right = !(m_emuControllers[3] & JOY_RIGHT) ;

	}
	/*
	else
	{
		Controller_1D_Left = 1 ;
		Controller_1D_Right = 1 ;
		Controller_1D_Up = 1 ;
		Controller_1D_Down = 1 ;
		Controller_1D_A = 1 ;
		Controller_1D_B = 1 ;
		Controller_1D_C = 1 ;
		Controller_1D_X = 1 ;
		Controller_1D_Y = 1 ;
		Controller_1D_Z = 1 ;
		Controller_1D_Start = 1 ;
		Controller_1D_Mode = 1 ;

		Controller_2C_Left = 1 ;
		Controller_2C_Right = 1 ;
		Controller_2C_Up = 1 ;
		Controller_2C_Down = 1 ;
		Controller_2C_A = 1 ;
		Controller_2C_B = 1 ;
		Controller_2C_C = 1 ;
		Controller_2C_X = 1 ;
		Controller_2C_Y = 1 ;
		Controller_2C_Z = 1 ;
		Controller_2C_Start = 1 ;
		Controller_2C_Mode = 1 ;
	
	}
*/

	return 0 ;
}


void CXBoxSample::xboxSaveState() 
{
	if ( g_statefile && strlen( g_statefile ) )
	{
		g_statefile[ strlen(g_statefile)-1 ] = '0' + m_stateNumber ;

		Save_State( g_statefile ) ;

		sprintf( global_error_message, "State %u Saved", m_stateNumber+1 ) ;
		m_msgDelay = 120 ;
	}
}

void CXBoxSample::xboxLoadState() 
{
	char szholder[500] ;

	if ( g_statefile && strlen( g_statefile ) )
	{
		if ( m_stateNumber == 0 )
		{
			g_statefile[ strlen(g_statefile)-1 ] = 'A' ;
			strcpy( szholder, g_statefile ) ;
			g_statefile[ strlen(g_statefile)-1 ] = '0' ;
			MoveFileEx( szholder, g_statefile, MOVEFILE_REPLACE_EXISTING ) ;
		}

		g_statefile[ strlen(g_statefile)-1 ] = '0' + m_stateNumber ;


		Load_State( g_statefile ) ;

		sprintf( global_error_message, "State %u Loaded", m_stateNumber+1 ) ;
		m_msgDelay = 120 ;
	}
}

void CXBoxSample::xboxChangeFilter() 
{
	g_app->m_xboxSFilter = (g_app->m_xboxSFilter+1)%NUM_SOFTWARE_FILTERS ;

	memset( g_pDeltaBuff, 0xFF, m_pitch*480 ) ;

	sprintf( global_error_message, "%s Filtering", SOFTWARE_FILTERS[m_xboxSFilter].name ) ;
	m_msgDelay = 120 ;
}

void CXBoxSample::xboxScreenshot() 
{
	mainprog_info wpng_info;
	char scr_filename[MAX_PATH] ;
	char scr_prefix[MAX_PATH] ;
	char dir[MAX_PATH] ;
	int maxnum = 0 ;
	HANDLE hFind;	
	WIN32_FIND_DATAA oFindData;


	CreateDirectory( m_screenshotDir, NULL ) ;

	sprintf( scr_prefix, "%s\\%s", m_screenshotDir, PLATFORM_NAME ) ; 

	CreateDirectory( scr_prefix, NULL ) ;

	sprintf( scr_prefix, "%s\\%s\\%s", m_screenshotDir, PLATFORM_NAME, strrchr(g_saveprefix, '\\')+1 ) ;

	CreateDirectory( scr_prefix, NULL ) ;

	sprintf( dir, "%s\\*.png", scr_prefix ) ;

	hFind = FindFirstFile( dir, &oFindData);

	if ( hFind != INVALID_HANDLE_VALUE) 
	{
		do
		{
			strcpy( scr_filename, oFindData.cFileName ) ;

			if ( strchr( scr_filename, '.' ) == NULL )
				continue ;

			*(strchr( scr_filename, '.' )) = 0 ;

			//sprintfx( "%s %u %s\r\n", scr_filename, strlen(scr_prefix), scr_filename + strlen(scr_prefix) ) ;

			if ( atoi( scr_filename ) > maxnum )
			{
				maxnum = atoi( scr_filename ) ;
			}
			
		} while (FindNextFile(hFind, &oFindData) ) ;
		FindClose( hFind );
	}

	maxnum++ ;

	if ( maxnum > 9999 )
		return ;

	sprintf( scr_filename, "%s\\%04.4u.png", scr_prefix, maxnum ) ;


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

	wpng_info.width = ((float)m_nScreenMaxX/m_gameVecScale.x);
	wpng_info.height = ((float)m_nScreenMaxY/m_gameVecScale.y) ;

	wpng_info.sample_depth = 8;

	wpng_info.bpp = 24 ;

	wpng_info.outfile = NULL;
	wpng_info.image_data = NULL;
	wpng_info.row_pointers = NULL;
	wpng_info.interlaced = false;
	wpng_info.have_bg = false;
	wpng_info.have_time = false;
	wpng_info.have_text = 0;
	wpng_info.gamma = 1.0;

    /* open the output file, or register an error and abort */
	if ((wpng_info.outfile = fopen( scr_filename, "wb") ) == NULL)
	{
		return ;
    }
	
	// allocate libpng stuff, initialize transformations, write pre-IDAT data
	

	int rc ;
	if ((rc=writepng_init(&wpng_info)) != 0)
	{
		fclose( wpng_info.outfile )  ;
		return ; 
		/*
		switch (rc)
		{
			case 2:
				fprintf(stderr, "WritePNG: libpng initialization problem (longjmp)\n");
			break;
			case 4:
				fprintf(stderr, "WritePNG: insufficient memory\n");
				break;
			case 11:
				fprintf(stderr, "WritePNG: internal logic error (unexpected PNM type)\n");
				break;
			default:
				fprintf(stderr, "WritePNG: unknown writepng_init() error\n");
				break;
        }
        exit(rc); */
    }
	
	long j;
	
	wpng_info.image_data = (unsigned char *)malloc( (wpng_info.bpp/8) * wpng_info.width);
		
	if (wpng_info.image_data == NULL)
	{
		writepng_cleanup(&wpng_info);
		fclose( wpng_info.outfile )  ;
		return ; 
		/*
		fprintf(stderr, "WritePNG:  insufficient memory for row data\n");
		writepng_cleanup(&wpng_info);
		cleanup();
		exit(5);
		*/
	}
		
	unsigned char *data ;
	

	RECT rectSource;
	rectSource.top = 0;
	rectSource.left = 0;
	rectSource.bottom = theHeight-1 ;
	rectSource.right  = theWidth-1 ;

	// Lock the rect in our texture
	D3DLOCKED_RECT d3dlr;
	Texture->LockRect(0, &d3dlr, &rectSource, 0);


	data = (unsigned char*)d3dlr.pBits;


	WORD pixel ;
		
	for (j = wpng_info.height;  j > 0L;  --j)
	{
		unsigned char* img_data = wpng_info.image_data;
		WORD *wdata = (WORD*)data;

		int i=0;

		for ( i = 0 ; i < wpng_info.width ; i++ )
		{
			pixel = wdata[i] ;
			img_data[2] = (pixel<<3) & 0xFF ;
			img_data[1] = ((pixel>>5)<<2) & 0xFF ;
			img_data[0] = ((pixel>>11)<<3) & 0xFF ;
			img_data += 3 ;
		}

		data += xbox_get_pitch();
			
	
			
		if( writepng_encode_row(&wpng_info) != 0)
		{
			writepng_cleanup(&wpng_info);
			free(wpng_info.image_data) ;
			fclose( wpng_info.outfile )  ;
			return ; 

/*			fprintf(stderr, "WritePNG:  libpng problem (longjmp) while writing row %ld\n",
			wpng_info.height-j);
			++error;
			break;*/
		}
	}
		
		/*
	if (error)
	{
		writepng_cleanup(&wpng_info);
		cleanup();
		exit(2);
	}
	*/
	if (writepng_encode_finish(&wpng_info) != 0)
	{
		//fprintf(stderr, "WritePNG:  error on final libpng call\n");
		writepng_cleanup(&wpng_info);
		free(wpng_info.image_data) ;
		fclose( wpng_info.outfile )  ;
		return ;
	}
	
	/* OK, we're done (successfully):  clean up all resources and quit */

	writepng_cleanup(&wpng_info);
	free(wpng_info.image_data) ;
	fclose( wpng_info.outfile )  ;

	sprintf( global_error_message, "%s", scr_filename) ;
	m_msgDelay = 120 ;
}

void CXBoxSample::xboxThrottle( int xthrottle ) 
{

	
	if ( xthrottle ) 
	{
		if ( throttle <= 0 )
			throttle = 10 ;
	}
	else
		throttle = 0 ;

}

void CXBoxSample::xboxChangeState() 
{
	m_stateNumber = (m_stateNumber+1)%10 ;

	sprintf( global_error_message, "Switched to State Slot %u", m_stateNumber+1 ) ;
	m_msgDelay = 120 ;
}

void CXBoxSample::xboxOptionsMenu( )
{
	int oldCDState ;

	oldCDState = g_app->m_cdda.m_bPaused ;

	g_app->m_state = IN_GAME_PAUSED ;
	g_app->m_sound.pause( TRUE ) ;
	g_app->m_cdda.pause(TRUE) ;
	//g_app->m_mp3player.pause( TRUE ) ;
	g_app->m_dwStartPause = GetTickCount();
	g_app->doCheatMenu() ;

	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;

	g_app->m_cdda.pause( oldCDState ) ;

	m_numFrames = 0 ;
	alwaysOff = 0 ;
	missVBlank = 0 ;
	m_startTime = GetTickCount() ;
}

void CXBoxSample::xboxStartRecording( )
{
	if ( m_emuRecording || m_emuPlaying )
		return ;


	m_sound.pause(TRUE ) ;
	m_cdda.pause(TRUE) ;
	FILE *checkfile ;

	while ( 1 )
	{
		pmenuParams = &(m_skin.popupMenu) ;

		m_mp3player.process() ;
		//m_plaything.Render( 0,0,0 ) ;



		swprintf( m_menuText[0], L"Confirm Start Recording" ) ;
		swprintf( m_menuText[1], L"" ) ;
		swprintf( m_menuText[2], L"WARNING" ) ;
		swprintf( m_menuText[3], L"This function is going to load the currently" ) ;
		swprintf( m_menuText[4], L"selected save state and start recording."   ) ;
		swprintf( m_menuText[5], L"" ) ;
		swprintf( m_menuText[6], L"Press B if you want to cancel this action." ) ;
		swprintf( m_menuText[7], L"Press Y to load the state and start recording.") ;

		renderPopupBkg( 8 ) ;
		renderMenuText( 0, 0, m_menuText, 8, 0 ) ;
		
		
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );


        XBInput_GetInput();

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			m_sound.pause(FALSE) ;
			m_cdda.pause(FALSE) ;
			return ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_Y])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;
			break ;
		}
	}

	xboxLoadState() ;

	checkfile = fopen( g_statefile, "rb" ) ;

	if ( checkfile == NULL )
	{
		xboxSaveState() ;
	}
	else
	{
		fclose( checkfile ) ;
	}

	m_emuRecordSlot = m_stateNumber ;
	m_emuRecordPosition = 0 ;
	m_emuRecording = 1 ;

	m_sound.pause(FALSE) ;
	m_cdda.pause(FALSE) ;

	sprintf( global_error_message, "Started Recording at Slot %u", m_emuRecordSlot+1 ) ;
	m_msgDelay = 120 ;

}

void CXBoxSample::xboxStopRecording( )
{
	if ( ! m_emuRecording )
		return ;

	char recname[500] ;
	FILE *recfile ;

	sprintf( recname, "%s.sr0", g_saveprefix ) ;

	recname[ strlen(recname)-1 ] = '0' + m_emuRecordSlot  ;


	recfile = fopen( recname, "wb") ;

	if ( recfile == NULL )
	{
		sprintf( global_error_message, "Could not open %s for writing", recname ) ;
		m_msgDelay = 120 ;
		return ;
	}

	fwrite( m_szEmuRecorder, sizeof(char), m_emuRecordPosition, recfile  ) ;
	fclose( recfile ) ;

	m_emuRecording = 0 ;

	sprintf( global_error_message, "Stopped Recording at Slot %u", m_emuRecordSlot+1 ) ;
	m_msgDelay = 120 ;
}
void CXBoxSample::xboxStartPlaying( )
{
	if ( m_emuPlaying || m_emuRecording )
		return ;

	char recname[500] ;
	FILE *recfile ;
	unsigned int filesize ;

	m_sound.pause(TRUE) ;
	m_cdda.pause(TRUE) ;
	while ( 1 )
	{
		pmenuParams = &(m_skin.popupMenu) ;

		m_mp3player.process() ;
		//m_plaything.Render( 0,0,0 ) ;



		swprintf( m_menuText[0], L"Confirm Start Playing" ) ;
		swprintf( m_menuText[1], L"" ) ;
		swprintf( m_menuText[2], L"WARNING" ) ;
		swprintf( m_menuText[3], L"This function is going to load the currently" ) ;
		swprintf( m_menuText[4], L"selected save state and start playing the recording."   ) ;
		swprintf( m_menuText[5], L"" ) ;
		swprintf( m_menuText[6], L"Press B if you want to cancel this action." ) ;
		swprintf( m_menuText[7], L"Press Y to load the state and start playing.") ;

		renderPopupBkg( 8 ) ;
		renderMenuText( 0, 0, m_menuText, 8, 0 ) ;
		
		
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );


        XBInput_GetInput();

		if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
		{
			m_sfxMenuCancel.Play( DSBPLAY_FROMSTART ) ;
			m_sound.pause(FALSE) ;
			m_cdda.pause(FALSE) ;
			return ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_Y])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;
			break ;
		}
	}

	m_emuRecordSlot = m_stateNumber ;

	sprintf( recname, "%s.sr0", g_saveprefix ) ;

	recname[ strlen(recname)-1 ] = '0' + m_emuRecordSlot  ;


	recfile = fopen( recname, "rb") ;

	if ( recfile == NULL )
	{
		sprintf( global_error_message, "Could not open %s for reading", recname ) ;
		m_msgDelay = 120 ;
		m_sound.pause(FALSE) ;
		return ;
	}

	fseek( recfile, 0, SEEK_END ) ;
	m_emuPlaySize = ftell( recfile ) ;
	fseek( recfile, 0, SEEK_SET ) ;

	fread( m_szEmuRecorder, sizeof(char), m_emuPlaySize, recfile ) ;
	fclose( recfile ) ;

	m_emuPlayPosition = 0 ;

	m_emuPlaying = 1 ;

	xboxLoadState() ;

	m_sound.pause(FALSE) ;
	m_cdda.pause(FALSE) ;

	sprintf( global_error_message, "Started Playing Slot %u", m_emuRecordSlot+1 ) ;
	m_msgDelay = 120 ;
}
void CXBoxSample::xboxStopPlaying( )
{
	if ( ! m_emuPlaying )
		return ;

	m_emuPlaying = 0 ;

	sprintf( global_error_message, "Stopped Playing Slot %u", m_emuRecordSlot+1 ) ;
	m_msgDelay = 120 ;
}
/*
void CXBoxSample::checkGeneralEvents( )
{

	static int did_save_state[4] = { 0, 0, 0, 0} ;
	static int did_load_state[4] = { 0, 0, 0, 0} ;
	static int did_change_state[4] = { 0, 0, 0, 0} ;
	static int did_screenshot[4] = { 0, 0, 0, 0} ;
	static int did_change_gfx[4] = { 0, 0, 0, 0} ;
	static int did_toggle_bgm[4] = { 0, 0, 0, 0} ;

	int throttle ;

	throttle = 0 ;


	for ( int i = 0; i < 4 ; i++ )
	{

		for ( int j = 0 ; j < 10 ; j++ )
		{
			if ( ( m_mappings[i].combos[j].mapping ) && ( ( m_xboxControllers[i] & m_mappings[i].combos[j].mapping ) == m_mappings[i].combos[j].mapping ) )
			{
				if ( m_mappings[i].combos[j].currmove == 0 )
				{
					m_mappings[i].combos[j].currmove = 1 ;
					m_mappings[i].combos[j].currdelay = m_mappings[i].combos[j].delay ;
				}
			}
			if ( m_mappings[i].combos[j].currmove )
			{
				if ( m_mappings[i].combos[j].currdelay )
				{
					m_mappings[i].combos[j].currdelay-- ;
					m_emuControllers[i] = m_mappings[i].combos[j].moves[ m_mappings[i].combos[j].currmove - 1] ;
				}
				else
				{
					m_mappings[i].combos[j].currmove++ ;
					if ( m_mappings[i].combos[j].currmove == m_mappings[i].combos[j].endmove + 1 )
					{
						m_mappings[i].combos[j].currmove = 0 ;
					}
					else
					{
						m_mappings[i].combos[j].currdelay = m_mappings[i].combos[j].delay ;
						m_emuControllers[i] = m_mappings[i].combos[j].moves[ m_mappings[i].combos[j].currmove - 1] ;
					}
				}
			}
		}

		if ( ( m_mappings[i].options_menu ) && ( ( m_xboxControllers[i] & m_mappings[i].options_menu ) == m_mappings[i].options_menu ) )
		{
			xboxOptionsMenu() ;
		}

		if ( ( m_mappings[i].save_state ) && ( ( m_xboxControllers[i] & m_mappings[i].save_state ) == m_mappings[i].save_state ) )
		{
			if ( ! did_save_state[i] )
			{
				xboxSaveState() ;
			}
			did_save_state[i] = 1 ;
		}
		else
		{
			did_save_state[i] = 0 ;
		}

		if ( ( m_mappings[i].load_state ) && ( ( m_xboxControllers[i] & m_mappings[i].load_state ) == m_mappings[i].load_state ) )
		{
			if ( ! did_load_state[i] )
			{
				xboxLoadState() ;
			}
			did_load_state[i] = 1 ;
		}
		else
		{
			did_load_state[i] = 0 ;
		}

		if ( ( m_mappings[i].change_save_slot ) && ( ( m_xboxControllers[i] & m_mappings[i].change_save_slot ) == m_mappings[i].change_save_slot ) )
		{
			if ( ! did_change_state[i] )
			{
				xboxChangeState() ;
			}
			did_change_state[i] = 1 ;
		}
		else
		{
			did_change_state[i] = 0 ;
		}


		if ( ( m_mappings[i].screenshot ) && ( ( m_xboxControllers[i] & m_mappings[i].screenshot ) == m_mappings[i].screenshot ) )
		{
			if ( ! did_screenshot[i] )
			{
				xboxScreenshot() ;
			}
			did_screenshot[i] = 1 ;
		}
		else
		{
			did_screenshot[i] = 0 ;
		}

		if ( ( m_mappings[i].change_gfx_filter ) && ( ( m_xboxControllers[i] & m_mappings[i].change_gfx_filter ) == m_mappings[i].change_gfx_filter ) )
		{
			if ( ! did_change_gfx[i] )
			{
				xboxChangeFilter() ;
			}
			did_change_gfx[i] = 1 ;
		}
		else
		{
			did_change_gfx[i] = 0 ;
		}

		if ( ( m_mappings[i].toggle_bgm ) && ( ( m_xboxControllers[i] & m_mappings[i].toggle_bgm ) == m_mappings[i].toggle_bgm ) )
		{
			if ( ! did_toggle_bgm[i] )
			{
				m_mp3player.pause( ! m_mp3player.m_bPaused ) ;
			}
			did_toggle_bgm[i] = 1 ;
		}
		else
		{
			did_toggle_bgm[i] = 0 ;
		}


		if ( ( m_mappings[i].sfx_vol_up ) && ( ( m_xboxControllers[i] & m_mappings[i].sfx_vol_up ) == m_mappings[i].sfx_vol_up ) )
		{
			m_sound.adjust_volume( 5 ) ;
		}
		if ( ( m_mappings[i].sfx_vol_down ) && ( ( m_xboxControllers[i] & m_mappings[i].sfx_vol_down ) == m_mappings[i].sfx_vol_down ) )
		{
			m_sound.adjust_volume( -5 ) ;
		}
		if ( ( m_mappings[i].bgm_vol_up ) && ( ( m_xboxControllers[i] & m_mappings[i].bgm_vol_up ) == m_mappings[i].bgm_vol_up ) )
		{
			m_mp3player.adjust_volume( 5 ) ;
		}
		if ( ( m_mappings[i].bgm_vol_down ) && ( ( m_xboxControllers[i] & m_mappings[i].bgm_vol_down ) == m_mappings[i].bgm_vol_down ) )
		{
			m_mp3player.adjust_volume( -5 ) ;
		}

		if ( ( m_mappings[i].throttle ) && ( ( m_xboxControllers[i] & m_mappings[i].throttle ) == m_mappings[i].throttle ) )
			throttle = 1 ;

	
	
	}

	xboxThrottle( throttle ) ;
}
*/

int ReadJoypad( int port )
{

	unsigned int value ;
	char xmsg[100] ;


	value = 0xFFFF ;

	if ( g_app->pollXBoxControllers() )
	{
		//Running = 0 ;
		g_app->m_state = MAIN_MENU ;
		return value ;
	}

	g_app->updateCheats2() ;

	g_app->checkGeneralEvents() ;	

	if ( g_app->m_bNetplay )
	{
		if ( g_app->m_bNetplay == 2 )  //server
		{
			g_app->m_emuControllers[1] = g_app->m_networkEmuControllers[0] ;
		}
		else //client
		{
			g_app->m_emuControllers[1] = g_app->m_emuControllers[0] ;
			g_app->m_emuControllers[0] = g_app->m_networkEmuControllers[0] ;
		}
	}

	value = ( ~(g_app->m_emuControllers[port] ) ) & 0xFFFF ;

	if ( g_app->m_state == MAIN_MENU )
	{
		value |= 0x10000 ;
		//Running = 0 ;
	}
/*	
	
	XBInput_GetInput();

	if ( g_Gamepads[port].hDevice )
	{

		if(g_Gamepads[port].wButtons & XINPUT_GAMEPAD_LEFT_THUMB )
		{
			g_app->m_state = IN_GAME_PAUSED ;
			g_app->m_sound.pause( TRUE ) ;
			g_app->m_cdda.pause(TRUE) ;
			g_app->m_mp3player.pause( TRUE ) ;
			g_app->m_dwStartPause = GetTickCount();
			g_app->doCheatMenu() ;

			if ( g_app->m_state == MAIN_MENU )
			{
				value |= 0x10000 ;
				Running = 0 ;
			}
		}
		if(g_Gamepads[port].wPressedButtons & XINPUT_GAMEPAD_RIGHT_THUMB )
		{
			if ( g_app->m_bitDepth == 16 )
				g_app->m_xboxSFilter = (g_app->m_xboxSFilter+1)%NUM_SOFTWARE_FILTERS ;
			else
				g_app->m_xboxSFilter = 0 ;
		}

		if ( g_app->getButtonState( port, g_app->m_bMappingCross ) )
			value &= ~JOY_CROSS ;
		if ( g_app->getButtonState( port, g_app->m_bMappingSquare ) )
			value &= ~JOY_SQUARE ;
		if ( g_app->getButtonState( port, g_app->m_bMappingTriangle ) )
			value &= ~JOY_TRIANGLE ;
		if ( g_app->getButtonState( port, g_app->m_bMappingCircle ) )
			value &= ~JOY_CIRCLE ;
		if ( g_Gamepads[port].wButtons & XINPUT_GAMEPAD_DPAD_LEFT )
			value &= ~JOY_LEFT ;
		if ( g_Gamepads[port].wButtons & XINPUT_GAMEPAD_DPAD_UP )
			value &= ~JOY_UP ;
		if ( g_Gamepads[port].wButtons & XINPUT_GAMEPAD_DPAD_RIGHT )
			value &= ~JOY_RIGHT ;
		if ( g_Gamepads[port].wButtons & XINPUT_GAMEPAD_DPAD_DOWN )
			value &= ~JOY_DOWN ;
		if ( g_app->getButtonState( port, g_app->m_bMappingStart ) )
			value &= ~JOY_START ;
		if ( g_app->getButtonState( port, g_app->m_bMappingSelect ) )
			value &= ~JOY_SELECT ;

		if ( g_app->getButtonState( port, g_app->m_bMappingR1 ) )
			value &= ~JOY_R1 ;
		if ( g_app->getButtonState( port, g_app->m_bMappingL1 ) )
			value &= ~JOY_L1 ;
		if ( g_app->getButtonState( port, g_app->m_bMappingR2 ) )
			value &= ~JOY_R2 ;
		if ( g_app->getButtonState( port, g_app->m_bMappingL2 ) )
			value &= ~JOY_L2 ;

		
		if ( ( g_Gamepads[port].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) && 
			 (g_Gamepads[port].bPressedAnalogButtons[XINPUT_GAMEPAD_WHITE]) )
		{
			LoadState( g_app->g_statefile ) ;
		}
		else if ( ( g_Gamepads[port].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) && 
			 (g_Gamepads[port].bPressedAnalogButtons[XINPUT_GAMEPAD_BLACK]) )
		{
			SaveState( g_app->g_statefile ) ;
		}

		//sprintf( xmsg, "x=%d,y=%d,x=%d,y=%d\r\n", g_Gamepads[port].sThumbRX, g_Gamepads[port].sThumbRX, g_Gamepads[port].fX2, g_Gamepads[port].fY2 ) ;

		if ( fabs(g_Gamepads[port].fX2) > 0.10f )
		{
			g_app->m_sound.adjust_volume( (int) ( g_Gamepads[port].fX2 * 25.0 ) ) ;
		}
		if ( fabs( g_Gamepads[port].fY2 ) > 0.10f )
		{
			g_app->m_cdda.adjust_volume( (int) ( g_Gamepads[port].fY2 * 25.0 ) ) ;
			g_app->m_mp3player.adjust_volume( (int) ( g_Gamepads[port].fY2 * 25.0 ) ) ;
		}

		if ( g_Gamepads[port].fX1 > 0.05f )
			value &= ~JOY_RIGHT ;

		if ( g_Gamepads[port].fX1 < -0.05f )
			value &= ~JOY_LEFT ;

		if ( g_Gamepads[port].fY1 > 0.05f)
			value &= ~JOY_UP ;
		
		if ( g_Gamepads[port].fY1 < -0.05f)
			value &= ~JOY_DOWN ;

	}

	if ( g_app->getButtonState( 0, g_app->m_bMappingThrottle ) > 200 )
	{
		iFastFwd = 1 ;
	}
	else
	{
		iFastFwd = 0 ;
	}
*/

	value = ((value>>8)&0xFF) | ( (value<<8) & 0xFF00 );
	return value ;
}






#define CD_SECS 60
#define CD_FRAMES 75

void CXBoxSample::loadCueSheet( char *cuefile ) 
{
	FILE  *infile ;
	char  *cuedata ;
	unsigned int filesize ;
	char  *line ;
	char  *rpos ;
	char  *npos ;
	char  *msf ;
	char  *stringpos ;
	byte  mins, secs, frms, track, tracktype ;
	char  trackfilename[256] ;
	char  *tok ;
	int   sectorA, sectorB ;
	char  *lastslashA ;
	char  *lastslashB ;
	//char  xmsg[100] ;
	int   totalsectors ;
	int smbfile ;
	int dosamba = 0 ;

	memset( trackfilename, 0, 256 ) ;
	memset( CD_track, 0, sizeof(CD_track) ) ;

	track = mins = secs = frms = 0 ;

	writexbox( "about to open cue\r\n" ) ;



	dosamba = ( ( strncmp( cuefile, "SMB:", 4 ) == 0 ) || ( strncmp( cuefile, "smb:", 4 ) == 0 ) ) ;

	if ( dosamba ) 
	{
		char smbfilename[1024] ;
		char *smbp ;
		FILE *outfile ;
		char *buf ;

		sprintf( smbfilename, "%s%s", m_smbShare, cuefile+4 ) ;

		while ( smbp = strchr( smbfilename, '\\' ) )
			*smbp = '/' ;

		smbfile = m_smb.open(  smbfilename, O_RDONLY|O_BINARY ) ;

		if ( smbfile <= 0  )
		{
			return ;
		}

		filesize = m_smb.lseek( smbfile, 0, SEEK_END ) ;
		m_smb.lseek( smbfile, 0, SEEK_SET ) ;

		cuedata = (char*)malloc( filesize+1 ) ;
		memset( cuedata, 0, filesize+1 ) ;

		m_smb.read( smbfile, cuedata, filesize ) ;

		m_smb.close( smbfile ) ;
	}
	else if ( m_bUsingRelax )
	{
		if ( m_relax.Open( cuefile ) )
		{
			filesize = m_relax.GetLength() ;

			cuedata = (char*)malloc( filesize+1 ) ;

			if ( !cuedata )
			{
				m_relax.Close() ;
				return ;
			}

			memset( cuedata, 0, filesize+1 ) ;

			if ( ! m_relax.ReadAll( cuedata, filesize ) )
			{
				free(cuedata) ;
				m_relax.Close() ;
				return ;
			}

			m_relax.Close() ;

		}
		else
		{
			return ;
		}
	}
	else
	{

		infile = fopen( cuefile, "rb" ) ;

		if ( !infile )
		{
			return ;
		}

		fseek( infile, 0, SEEK_END ) ;
		filesize = ftell( infile ) ;
		fseek( infile, 0, SEEK_SET ) ;

		//sprintf( xmsg, "cuesize=%u\r\n", filesize ) ;
		//writexbox( xmsg ) ;

		cuedata = (char*)malloc( filesize+1 ) ;
		memset( cuedata, 0, filesize+1 ) ;

		fread( cuedata, sizeof(char), filesize, infile ) ;

		fclose( infile ) ;
	}

	writexbox( "allocated and closed file\r\n" ) ;

	line = cuedata ;


	while ( *line )
	{
		writexbox( "top loop\r\n" ) ;

		rpos = strchr( line, '\r' ) ;
		npos = strchr( line, '\n' ) ;

		if ( npos > rpos )
			rpos = npos ;

		if ( rpos )
			*rpos = 0 ;

		writexbox( "removed trailing line\r\n" ) ;

		strupr( line ) ;

		//writexbox( line ) ;
		//writexbox( "\r\n" ) ;

		if ( stringpos = strstr( line, "TRACK " ) )
		{
			writexbox( "gottrack\r\n" ) ;
			if ( strstr( line, "AUDIO" ) )
				tracktype = 0 ;
			else
				tracktype = 4 ;

			tok = strtok( stringpos+5, " \t\r\n" ) ;


			track = atoi( tok ) ;


			if ( ( track < 0 ) || ( track > 255 ) )
			{
				track = 255 ;
			}


		}
		else if ( ( stringpos = strstr( line, "INDEX 1 " ) ) || ( stringpos = strstr( line, "INDEX 01 " ) ) )
		{
			writexbox( "gotindex\r\n" ) ;
			msf = strtok( stringpos+8, " \t\r\n" ) ;
			if ( strlen(msf) >= 8 )
			{
				*(msf+2) = 0 ;
				*(msf+5) = 0 ;
				*(msf+8) = 0 ;

				mins = atoi( msf ) ;
				secs = atoi( msf+3 ) ;
				frms = atoi( msf+6 ) ;

				if ( secs > 57 )  //account for standard gap that seems to appear on all cue sheets
				{
					secs = secs + 2 - 60 ;
					mins++ ;
				}
				else
				{
					secs += 2 ;
				}
			}
			CD_track[track].beg_fra = frms ;
			CD_track[track].beg_min = mins ;
			CD_track[track].beg_sec = secs;  
			CD_track[track].type = tracktype ;
			strcpy( CD_track[track].filename, trackfilename ) ;
		}
		else if ( stringpos = strstr( line, "FILE " ) )
		{
			writexbox( "gotfile\r\n" ) ;
			tok = strtok( stringpos+4, " \r\n\t\"" ) ;

			lastslashA = strrchr( tok, '/' ) ;
			lastslashB = strrchr( tok, '\\' ) ;

			if ( lastslashB > lastslashA )
				lastslashA = lastslashB ;

			if ( lastslashB )
			{
				*lastslashB = 0 ;
				tok = lastslashB + 1 ;
			}
			
			if ( dosamba )
			{
				char holder[500] ;
				char *smbp ;

				strcpy(holder, cuefile ) ;

				*strrchr( holder, '\\' ) = 0 ;

				strlwr(tok) ;
				sprintf( trackfilename, "%s%s\\%s", m_smbShare, holder+4, tok ) ;

				while ( smbp = strchr( trackfilename, '\\' ) )
					*smbp = '/' ;
			}
			else
			{
				strcpy( trackfilename, m_szCurrentDir ) ;
				strcat( trackfilename, tok ) ;

				//sprintfx( trackfilename ) ;
			}

		}

		line = rpos + 1 ;

		if ( line - cuedata >= filesize )
			break ;

	}

	nb_max_track = track ;
	totalsectors = 0 ;


	for ( int i = 1 ; i <= nb_max_track ; i++ )
	{

		if ( i == nb_max_track )
		{
			sectorB = 73 * CD_SECS * CD_FRAMES ; 
	
			sectorA = ( CD_track[i].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i].beg_sec * CD_FRAMES ) +
					  ( CD_track[i].beg_fra  )  ;
	
			CD_track[i].length = sectorB - sectorA ;
		}
		else
		{
			sectorB = ( CD_track[i+1].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i+1].beg_sec * CD_FRAMES ) +
					  ( CD_track[i+1].beg_fra  )  ;
	
			sectorA = ( CD_track[i].beg_min * CD_SECS * CD_FRAMES ) +
					  ( CD_track[i].beg_sec * CD_FRAMES ) +
					  ( CD_track[i].beg_fra  )  ;
	
			CD_track[i].length = sectorB - sectorA ;
		}

		CD_track[i].beg_lsn = totalsectors;	

		totalsectors += CD_track[i].length ;

		//sprintf(xmsg, "trk=%u,type=%u,min=%u,sec=%u,fra=%u,lsn=%u,length=%ufilename=%s\r\n", i, CD_track[i].type, 
			//bcdbin[CD_track[i].beg_min], bcdbin[CD_track[i].beg_sec], bcdbin[CD_track[i].beg_fra], 
			//CD_track[i].beg_lsn, CD_track[i].length, CD_track[i].filename ) ;
		//writexbox( xmsg ) ;
	}

	free (cuedata) ;

	writexbox( "returning from cue\r\n" ) ;

}



void CXBoxSample::initConsole( UINT32 idx, int isFavorite )
{
	char                filename[500] ;
	char                caseval[500] ;
	char systemcard[200] ;
	int isSelectMenu = 1 ;
	int copySamba = 1 ;
	char tmpfilename[500] ;
	char shortpath[100] ;
	int isoOrBin = 0 ;

	global_error_message[0] = 0 ;

	sleepamount = 0 ;

	m_numFrames = 0 ;
	m_startTime = GetTickCount() ;
	m_droppedFrames = 0 ;
	m_currentStartSector = 9999999 ;

//	soundChannels = 0xFF ;
//	bkgHalt = 0 ;


	throttle = 0 ;
	blittermode = 1 ;

	memset( m_memMatches, 1, CONSOLE_MEMORY_SIZE ) ;
	m_currentMemMatches = CONSOLE_MEMORY_SIZE ;
	m_numCheats = 0 ;

	nb_max_track = 0 ;


	
	if ( isFavorite )
	{
		strcpy( (char*)filename, m_filesFavorites[idx].filename ) ;
	}
	else
	{
		if ( g_autoLaunchGame )
		{
			strcpy( (char*)filename, g_launchData.szFilename ) ;
		}
		else
		{
			strcpy((char*)filename, m_szCurrentDir ) ;
			strcat( (char*)filename, (const char*)files[idx].filename ) ;
		}
	}

	
	

	sprintfx( "initconsole %s\r\n", filename ) ;

	loaded_cue = 0 ;

	memset( CD_track, 0, sizeof(CD_track) ) ;


	strcpy( g_cuefile, "" ) ;


	char *p;


	if ( strlen( strrchr( filename, '\\' )+1 ) > 42 )
	{
		strncpy( shortpath, strrchr( filename, '\\' )+1, 42 ) ;
		shortpath[42] = 0 ;

		p = strrchr( filename, '.' ) ;

		if ( p )
		{
			strcpy( shortpath+( 41 - strlen(p) ), p ) ;
		}
	}
	else
	{
		strcpy( shortpath, strrchr( filename, '\\' )+1 ) ;
	}

	while( strchr( shortpath, ',' ) )
		*strchr( shortpath, ',' ) = '_' ;


	//writexbox( "init1" ) ;

	strcpy( g_saveprefix, g_savePath ) ;
	strcat( g_saveprefix, "\\" ) ;
	strcat( g_saveprefix, shortpath ) ;
	//sprintf(saveprefix, "%s\\%s", savedir, (const char*)files[idx].filename);
	p = strchr(g_saveprefix, '.');
	if (p) *p = 0;

	strcpy(g_sramfile, g_saveprefix);
	strcat(g_sramfile, ".srm");

	strcpy(g_keysfile, g_saveprefix);
	strcat(g_keysfile, ".key");

	strcpy(g_settingsfile, g_saveprefix);
	strcat(g_settingsfile, ".stg");

	strcpy(g_bramfile, g_saveprefix);
	strcat(g_bramfile, ".brm");

	strcpy(g_chtfile, g_saveprefix);
	strcat(g_chtfile, ".cht");

	sprintf( g_statefile, "%s.sta", g_saveprefix ) ;


	sprintfx( "initconsole\r\n") ;


	strcpy( caseval, filename ) ;

	m_bUsingSamba = ( strncmp( filename, "SMB:", 4 ) == 0 ) || ( strncmp( filename, "smb:", 4 ) == 0 ) ;
	m_bUsingRelax = ( strncmp( filename, "RLX:", 4 ) == 0 ) || ( strncmp( filename, "rlx:", 4 ) == 0 ) ;

	if (strstr (strupr(filename), ".MP3"))
	{
		if ( m_mp3player.loadFile( caseval, 1, 0, 70*60*75 ) )
		{
			popupMsg( "Could not load MP3 file", &m_pnlBackgroundSelect ) ;
			return ;
		}
		else
		{
			m_mp3player.insertSilence( 22050 ) ;
			m_mp3player.pause( FALSE ) ;
			m_state = MAIN_MENU ;
			return  ;
		}
	}
	else if ( (strstr (filename, ".M3U")) || (strstr (filename, ".m3u")) )
	{
		if ( m_mp3player.loadPlaylist( caseval ) )
		{
			popupMsg( "Could not load M3U playlist", &m_pnlBackgroundSelect ) ;
			//writexbox( "nonomp3\r\n") ;
			return ;
		}
		else
		{
			//m_mp3player.insertSilence( 22050 ) ;
			m_mp3player.pause( FALSE ) ;
			m_state = MAIN_MENU ;
			return  ;
		}
	}
	else if (strstr (strupr(filename), ".CUE"))
	{
		writexbox( "processing cue\r\n" ) ;

		strcpy( g_cuefile, caseval ) ;
		loadCueSheet( g_cuefile ) ;
		filename[0] = 0 ;

		for ( int i = 0 ; i < nb_max_track ; i++ )
		{
			if ( CD_track[i].type == 4 )
			{
				strcpy( filename, CD_track[i].filename ) ;
				break ;
			}
		}

		//sprintf( xmsg, "filename fom cue=%s", filename ) ;
		//writexbox( xmsg ) ;

		if ( filename[0] == 0 )
		{
			m_state = MAIN_MENU ;
			return ;
		}

		sprintfx( "cue isofile = %s\r\n", filename ) ;

		loaded_cue = 1 ;
		copySamba = 0 ;

		if ( ( strstr( filename, ".ISO" ) ) || ( strstr( filename, ".iso" ) ) )
		{
			copySamba = 0 ;
			isoOrBin = 1 ;
		}
		else if ( ( strstr( filename, ".BIN" ) ) || ( strstr( filename, ".bin" ) ) )
		{
			copySamba = 0 ;
			isoOrBin = 2 ;
		}

	}
	else if ( strstr( filename, ".ISO" ) )
	{
		copySamba = 0 ;
		isoOrBin = 1 ;
	}
	else if ( strstr( filename, ".BIN" ) )
	{
		copySamba = 0 ;
		isoOrBin = 2 ;
	}





	memset( m_mp3player.m_pSoundBufferData, 0, m_mp3player.stream_buffer_size) ;


	if ( loadSettings( g_settingsfile ) )
	{
		changeMenu( &m_skin.gameSelectMenu, &m_skin.otherMenu ) ;
		doConfigureGame( g_settingsfile, g_keysfile ) ;
		isSelectMenu = 0 ;
	}
	else
	{
		loadKeys( g_keysfile ) ;
	}

	memset( m_mp3player.m_pSoundBufferData, 0, m_mp3player.stream_buffer_size) ;

	sprintfx( "initconsole\r\n") ;

	if ( m_bNetplay )
	{
		if ( setupNetplay() )
			return ;
	}

	if ( g_autoLaunchGame )
	{
		m_pnlSplashGame.Render() ;
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
	}
	else
	{
		if ( isSelectMenu )
		{
			doTransition( &m_pnlBackgroundSelect, &m_pnlSplashGame, m_skin.fade, 1 ) ;
		}
		else
		{
			doTransition( &m_pnlBackgroundOther, &m_pnlSplashGame, m_skin.fade, 1 ) ;
		}
	}

	if ( !m_bBgmInGame )
	{
		m_mp3player.pause( TRUE ) ;
	}
	memset( m_mp3player.m_pSoundBufferData, 0, m_mp3player.stream_buffer_size) ;

	sprintfx("initconsole\r\n") ;


	m_plaything.FreeSprites() ;

	sprintf( tmpfilename, "%s\\%s\\SPRITES\\*", m_szSkinDir, m_szSkin) ;



	if ( m_bUsingSamba && !loaded_cue)
	{
		char smbfilename[1024] ;
		char *smbp ;
		FILE *outfile ;
		char *buf ;

		strcpy( filename, caseval) ;

		sprintf( smbfilename, "%s%s", m_smbShare, filename+4 ) ;

		while ( smbp = strchr( smbfilename, '\\' ) )
			*smbp = '/' ;

		sprintfx( "samba:%s\r\n", smbfilename ) ;


		sprintfx( "samba:%s\r\n", smbfilename ) ;


		strcpy( filename, smbfilename ) ;

		sprintfx( "samba:%s\r\n", smbfilename ) ;

		if ( copySamba )
		{

			m_smbCdFile = m_smb.open( smbfilename,O_RDONLY|O_BINARY);

			if ( m_smbCdFile <= 0 )
			{
				popupMsg( "Could not open SMB file", &m_pnlBackgroundSelect ) ;
				m_plaything.LoadSprites( tmpfilename ) ;
				return ;
			}

			sprintfx( "copy samba\r\n") ;

			int filesize = m_smb.lseek(m_smbCdFile,0,SEEK_END);
			m_smb.lseek(m_smbCdFile,0,SEEK_SET);

			sprintfx( "copy samba\r\n") ;

			sprintf( filename, "X:\\%s", shortpath ) ;

			sprintfx( "copy samba %s %d\r\n", filename, filesize ) ;

			outfile = fopen( filename, "wb") ;

			sprintfx( "copy samba\r\n") ;
			if ( outfile == NULL )
			{
				m_smb.close( m_smbCdFile ) ;
				popupMsg( "Could not open X:\\ file for writing - perhaps X: is full?", &m_pnlBackgroundSelect ) ;
				m_plaything.LoadSprites( tmpfilename ) ;
				return ;
			}

			sprintfx( "copy samba\r\n") ;

			xbox_print_memory() ;

			buf = (char*) malloc(filesize) ;

			if ( buf == NULL )
			{
				popupMsg( "Could not allocate memory for copy samba", &m_pnlBackgroundSelect) ;
				m_plaything.LoadSprites( tmpfilename ) ;
				return ;
			}

			sprintfx( "copy samba\r\n") ;

			m_smb.read(m_smbCdFile,buf, filesize) ;

			sprintfx( "copy samba\r\n") ;

			fwrite( buf, 1, filesize, outfile ) ;
			fclose( outfile) ;
			m_smb.close( m_smbCdFile ) ;

			sprintfx( "copy samba\r\n") ;

			free(buf) ;
		}

	}
	else if ( m_bUsingRelax && !loaded_cue )
	{
		char rlxfilename[1024] ;
		FILE *outfile ;
		int filesize ;
		char *fbuf ;

		if ( copySamba )
		{
			if ( m_relax.Open( filename ) )
			{
				sprintfx( "opened rlx %s\r\n", filename ) ;
				filesize = m_relax.GetLength() ;


				sprintf( rlxfilename, "X:\\%s", shortpath ) ;
				strcpy(filename, rlxfilename) ;

				outfile = fopen(filename, "wb") ;

				if ( outfile == NULL )
				{
					m_relax.Close( ) ;
					m_plaything.LoadSprites( tmpfilename ) ;
					return ;
				}


				fbuf = (char*) malloc( filesize ) ;

				if ( !fbuf )
				{
					m_relax.Close() ;
					m_plaything.LoadSprites( tmpfilename ) ;
					return ;
				}

				if ( ! m_relax.ReadAll( fbuf, filesize ) )
				{
					free(fbuf) ;
					m_relax.Close() ;
					m_plaything.LoadSprites( tmpfilename ) ;
					return ;
				}

				m_relax.Close() ;

				fwrite( fbuf, 1, filesize, outfile ) ;
				fclose( outfile ) ;
				free(fbuf) ;
			}
			else
			{
				m_plaything.LoadSprites( tmpfilename ) ;
				return ;
			}
		}

	}


//	nonoise = 0 ;
	

	m_sound.init() ;
	m_cdda.init() ;
	//m_mp3player.init() ;

	//writexbox( "init1" ) ;
	cht_load() ;
	ggenie_init() ;

	// Create our texture
	init_texture();


	// Create our sprite driver
	if ( Sprite == NULL )
		D3DXCreateSprite(m_pd3dDevice, &Sprite);
	





	m_fAppTime = 0.0f ;

	g_dwStartTime = GetTickCount() ;
	g_dwTimePaused = 0 ;
	m_dwStartPause = 0 ;

	m_steps = 0 ;

	//writexbox( "init4" ) ;
	//Then start it up

	//m_sound.insertSilence( 22050 ) ;
	m_sound.pause( FALSE ) ;
	m_cdda.pause( FALSE ) ;
	//m_mp3player.insertSilence( 22050 ) ;
	//m_mp3player.pause( FALSE ) ;

//	hugomain( filename, g_sramfile, g_saveprefix, systemcard, 0, forceUS ) ;

	sprintfx("initconsole\r\n") ;

	m_state = IN_GAME ;

	QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev);

	gensmain(filename,m_countryCode,m_cdMethod,0, isoOrBin && m_bUsingSamba, isoOrBin && m_bUsingRelax,
		xbox_Fast_Blur,
		xbox_Sprite_Over,
		xbox_YM2612_Improv,
		xbox_DAC_Improv,
		xbox_PSG_Improv,
		xbox_MSH2_Speed,
		xbox_SSH2_Speed,
		xbox_Show_LED ) ;

	m_plaything.LoadSprites( tmpfilename ) ;
	//writexbox( "initout" ) ;
	m_state=MAIN_MENU ;
	saveKeys( g_keysfile ) ;
	saveSettings( g_settingsfile ) ;
	cleanupConsole() ;

	//put 3 frames of data in the audio buffer
	//processEmu(FALSE) ;
	//processEmu(FALSE) ;
	//processEmu(FALSE) ;


}

void CXBoxSample::cleanupConsole( )
{
	//sram_save();
	//rtc_save();
	cht_save() ;


	if (m_cheatCodes != NULL)
	{
		free(m_cheatCodes);
		m_cheatCodes = NULL;
	}


}



#ifdef __cplusplus
extern "C" {
#endif


void sprintfx( const char *fmt, ... )
{
    va_list	va;
    va_start(va, fmt);
	vsprintf( gxmsg, fmt, va);
	va_end( va ) ;
	writexbox(gxmsg) ;
}


unsigned int xbox_getfix_Xa()  //disable xa
{
	return g_app->m_psxfix_Xa ;
}
unsigned int xbox_getfix_Sio()  //always sio irq on
{
	return g_app->m_psxfix_Sio ;
}
unsigned int xbox_getfix_Mdec()   //b/w movies
{
	return g_app->m_psxfix_Mdec ;
}
unsigned int xbox_getfix_Cdda()  //disable cdda
{
	return g_app->m_psxfix_Cdda ;
}
unsigned int xbox_getfix_Cpu()   //cpu interpreter (slow, maybe more compatible)
{
	return g_app->m_psxfix_Cpu ;
}
unsigned int xbox_getfix_SpuIrq()  //always spu irq on
{
	return g_app->m_psxfix_SpuIrq ;
}
unsigned int xbox_getfix_VSyncWA()   // InuYasha Sengoku Battle fix
{
	return g_app->m_psxfix_VSyncWA ;
}


/*
long xbox_play_cdda( unsigned char *msf )
{
	unsigned long sector = ( msf[0] * 75 * 60 ) + ( msf[1] * 75 ) + msf[2];
	unsigned long sectorEnd ;
	unsigned long sectorTest ;
	unsigned int whichTrack ;

	whichTrack = 99 ;

	for ( int i = 0 ; i < g_app->m_numtracks ; i++ )
	{
		sectorTest = ( g_app->m_toc.tracks[i].addr[1] * 60 * 75 ) + 
					( g_app->m_toc.tracks[i].addr[2] * 75 ) +
					( g_app->m_toc.tracks[i].addr[3]  )  ;

		if ( sector < sectorTest )
		{
			whichTrack = i ;
			break ;
		}
	}

	if ( whichTrack == 99 )
	{
		sectorEnd = 999999 ;
	}
	else
	{
		sectorEnd = ( g_app->m_toc.tracks[whichTrack].addr[1] * 60 * 75 ) + 
					( g_app->m_toc.tracks[whichTrack].addr[2] * 75 ) +
					( g_app->m_toc.tracks[whichTrack].addr[3]  )  ;
	}

	//sprintfx("play cdda %u\r\n", sector ) ;

	g_app->m_cdda.play_sectors_file( sector, 999999, 1 ) ;

	return 0 ;
}
*/
long xbox_stop_cdda() 
{
	//writexbox("stop cdda\r\n") ;
	g_app->m_cdda.stop() ;
	return 0 ;
}

unsigned int xbox_get_vandal_heart_fix() 
{
	return g_app->m_vandalFix ;
}

DWORD xbox_get_bit_depth() 
{
	return g_app->m_bitDepth ;

}

void xbox_set_memory_ptr( unsigned char *ptr )
{
}

unsigned int xbox_get_framelimit() 
{
	return g_app->m_framelimit ;
}
unsigned int xbox_get_frameskip() 
{
	return g_app->m_frameskip ;
}
unsigned int xbox_get_graphics_fixes() 
{
	//sprintfx("graphicfix=%02.2X\r\n", g_app->m_graphicsFixes ) ;

	return g_app->m_graphicsFixes ;
}

void xbox_clear_screen()
{
	g_app->ClearScreen() ;
}

unsigned char* xbox_get_biosfile() 
{
	return g_app->m_biosfile ;
}

unsigned char* xbox_get_memcard1() 
{
	return g_app->m_memcard1 ;
}

unsigned char* xbox_get_memcard2() 
{
	return g_app->m_memcard2 ;
}

unsigned char* xbox_get_saveprefix()
{
	return (unsigned char*)g_app->g_saveprefix ;
}

unsigned long xbox_get_bytes_buffered() 
{
	//return g_app->m_sound.get_buffered_bytes() ;
	return 0 ;
}

unsigned int xbox_get_pitch()
{
	return g_app->m_pitch ;
}

unsigned char *xbox_cdbuffer() 
{

	return (g_app->m_ptrCdBuf)+12 ;
}

void xbox_get_td(unsigned char track, unsigned char *buffer) 
{
	unsigned int lu ;
	int whichTrack ;
	unsigned char b ;

	if ( track==0 )
		whichTrack = g_app->m_toc.lastTrack-1 ;
	else
		whichTrack = track-1 ;

	int val = 	( g_app->m_toc.tracks[whichTrack].addr[1] * 60 * 75 ) + 
				( g_app->m_toc.tracks[whichTrack].addr[2] * 75 ) +
				( g_app->m_toc.tracks[whichTrack].addr[3]  )  ;

/*
	if ( track == 0 )
	{
		val = ( ( 50*60 + 53 )*75 ) + 45 + 150 ;
	}
	else if ( track == 1 )
	{
		val = 150 ;
	}
	else if ( track == 2 )
	{
		val = ( ( 50*60 + 53 )*75 ) + 45 + 150 ;
	}
*/

	buffer[2] = (unsigned char)(val%75);
	val/=75;
	buffer[1]=(unsigned char)(val%60);
	buffer[0]=(unsigned char)(val/60);

	b=buffer[0];                                          // swap infos (psemu pro/epsxe)
	buffer[0]=buffer[2];
	buffer[2]=b;


}

void xbox_get_tn(unsigned char *ptr) 
{
	ptr[0]=1 ;
	ptr[1]=g_app->m_numtracks ;

}
void xbox_feed_stream(unsigned char* pSound,long lBytes) 
{
//	g_app->m_sound.process(pSound, lBytes ) ;
	//g_app->m_mp3player.process() ;
	//g_app->m_cdda.process() ;
}

int xbox_read_sector_type( unsigned int sector, unsigned int sector_type ) 
{
	unsigned char szbuf[6] ;
	DWORD numread ;
	//DWORD begintime, endtime ;
	//static DWORD totaltime = 1 ;
	//static DWORD iters = 0 ;
	//static DWORD cacheiters = 0 ;
	//static float avg = 0.0 ;

	//begintime = GetTickCount() ;

	//sprintfx("read sector %u\r\n", sector  ) ;

	if ( ( sector < g_app->m_currentStartSector ) || ( sector >= g_app->m_currentStartSector + CD_BUF_SECTORS ) )
	{
		if ( g_app->m_bRealCD )
		{
			memset( g_app->m_cdDataBuffer,0,2352) ;
			//for ( int i = 0 ; i < CD_BUF_SECTORS ; i++ )
				//g_app->m_io.ReadXASector( g_app->m_hCdrom, sector, CD_BUF_SECTORS, g_app->m_cdDataBuffer ) ;
				g_app->m_io.ReadXASector2( sector, CD_BUF_SECTORS, g_app->m_cdDataBuffer ) ;

			//sprintfx( "read %u bytes from CD\r\n", numread ) ;

		}
		else
		{
			if ( g_app->m_bNetworkCD )
			{
				memcpy( szbuf, &sector, 4 ) ;
				szbuf[4] = 2 + sector_type ; //psx is all XA data (2) + 1 for data or 0 for cdda

				g_app->m_sockNetplay.Send( szbuf, 5 ) ;
				numread = g_app->m_sockNetplay.Recv( g_app->m_cdDataBuffer, 2352 ) ;

//				sprintfx("read sector %u bytes %u\r\n", sector, numread ) ;

				while ( numread < 2352 )
				{
					numread += g_app->m_sockNetplay.Recv( g_app->m_cdDataBuffer+numread, 2352-numread ) ;
					//sprintfx("read sector %u bytes %u\r\n", sector, numread ) ;
				}

			}
			else
			{
				if ( g_app->m_bUsingSamba )
				{
					g_app->m_smb.lseek(g_app->m_smbCdFile,sector*2352,SEEK_SET);
					g_app->m_smb.read(g_app->m_smbCdFile,g_app->m_cdDataBuffer, 2352*CD_BUF_SECTORS ) ;
				}
				else
				{
					gzseek( g_app->m_cdfile, 2352*sector, SEEK_SET ) ;
					gzread( g_app->m_cdfile , g_app->m_cdDataBuffer, 2352*CD_BUF_SECTORS ) ;
				}
			}
		}


		g_app->m_currentStartSector = sector ;
	}
	else
	{
		//cacheiters++ ;
		//sprintfx("read sector %u from cache\r\n", sector  ) ;
	}
/*
	if ( sector==16 ) 
	{
		unsigned char dumpsec[200] ;

		for ( int i = 0 ; i < 16 ; i++ )
		{
			for ( int j = 0 ; j < 16 ; j++ )
			{
				sprintf( (char*)(dumpsec+3*j), "%2.2X ", *(g_app->m_cdDataBuffer+(i*16)+j) ) ;
			}
			dumpsec[48] = 0 ;
			sprintfx( "%s \r\n",dumpsec ) ;
		}
	}
*/
	g_app->m_ptrCdBuf = g_app->m_cdDataBuffer + ((sector-g_app->m_currentStartSector)*2352) ;

/*
	for ( int ii = 0 ; ii < 16 ; ii++ )
	{
		char msg[100] ;

		sprintf(msg, "%02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X \r\n",
			g_app->m_ptrCdBuf[(ii*16)+0], g_app->m_ptrCdBuf[(ii*16)+1], g_app->m_ptrCdBuf[(ii*16)+2], g_app->m_ptrCdBuf[(ii*16)+3], g_app->m_ptrCdBuf[(ii*16)+4], 
			g_app->m_ptrCdBuf[(ii*16)+5], g_app->m_ptrCdBuf[(ii*16)+6], g_app->m_ptrCdBuf[(ii*16)+7], g_app->m_ptrCdBuf[(ii*16)+8], g_app->m_ptrCdBuf[(ii*16)+9], 
			g_app->m_ptrCdBuf[(ii*16)+10], g_app->m_ptrCdBuf[(ii*16)+11], g_app->m_ptrCdBuf[(ii*16)+12], g_app->m_ptrCdBuf[(ii*16)+13], g_app->m_ptrCdBuf[(ii*16)+14], g_app->m_ptrCdBuf[(ii*16)+15] ) ;
		writexbox(msg) ;
	}
*/
	/*
	for ( unsigned int i = 0 ; i < 60000 ; i++ )
	{
		numread = (5+numread) * (numread+1) ;
		avg = (avg+4.234) / ( avg+1.23) ;
	}

	iters++ ;
	endtime = GetTickCount() ;

	totaltime += (endtime - begintime ) ;

	avg = (float)totaltime / (float)iters ; 

	if ( ( begintime%1000 >= 0 ) && ( begintime%1000 < 10 ) )
		sprintfx( "avgreadtime = %f, citer/iter = %u/%u %f\r\n", avg, cacheiters, iters, (float)cacheiters/(float)iters ) ;
*/
	return 0 ;
	//memset(g_app->m_cdbuffer, 0, 2352) ;

	//return ( g_app->m_io.ReadSectorMode2( g_app->m_hCdrom, sector, (LPSTR)g_app->m_cdbuffer ) == -1 ) ;
}


int xbox_read_sector_cdda( unsigned int sector ) 
{
	return xbox_read_sector_type( sector,0 ) ;
}

unsigned long xbox_gettime()
{
	
	FILETIME ft ;

	GetSystemTimeAsFileTime( &ft ) ;

	return 0 ;
	//return ft.dwLowDateTime / 100 ;
	
	//return GetTickCount() ;
}
unsigned long xbox_gettime2()
{
	
	return GetTickCount() ;
}

void xbox_loading_msg( LPCTSTR msg ) 
{
//	g_app->WriteLoadMessage(msg) ;

}

void xbox_exception_msg( LPCTSTR msg ) 
{
	//g_app->WriteExceptionMessage(msg) ;

}

unsigned int xbox_read_input(int port) 
{
	return 0 ;
}

unsigned char * xbox_get_screen_buffer()
{
	return g_app->g_pBlitBuff ;

}




void xbox_stop_cd()
{
	g_cdda->stop() ;

}
void xbox_read_cd_sector( unsigned char *p, unsigned int sector ) 
{
	int result ;
	char xmsg[100] ;

	//result = g_app->m_io.ReadSector( g_app->m_hCdrom, sector, (LPSTR)p ) ;



	if ( ( sector < g_app->m_currentStartSector ) || ( sector >= g_app->m_currentStartSector + CD_BUF_SECTORS ) )
	{
		result = g_app->m_io.ReadSomeSectors( g_app->m_hCdrom, sector, (LPSTR)g_app->m_cdDataBuffer, CD_BUF_SECTORS ) ;

		g_app->m_currentStartSector = sector ;
	}

	memcpy( p, g_app->m_cdDataBuffer + ((sector-g_app->m_currentStartSector)*2048), 2048) ;


}
void xbox_play_cdda( unsigned int sectorFrom, unsigned int sectorTo, unsigned char repeat ) 
{
	sprintfx( "play cdda %u %u\r\n", sectorFrom, sectorTo ) ;

	g_cdda->play_sectors( sectorFrom, sectorTo, repeat, g_app->m_hCdrom ) ;
}

char* xbox_get_track_name( int tnum ) 
{
	if ( tnum > g_app->nb_max_track )
		return "xxxx" ;
	else
		return g_app->CD_track[tnum].filename ;
}

int xbox_get_track_length( int tnum ) 
{
	if ( tnum > g_app->nb_max_track )
		return 0 ;
	else
		return g_app->CD_track[tnum].length ;
}


char* xbox_get_bramfile()
{
	return g_app->g_bramfile ;
}

char* xbox_get_savepath()
{
	return g_app->g_savePath ;
}

int xbox_sread( void *buf, int size1, int size2, int fd )
{
	//sprintfx( "read %u %u %d\r\n", size1, size2, fd ) ;

	return g_app->m_smb.read( fd, buf, size1*size2 ) ;

	//sprintfx( "reade %u %u %d\r\n", size1, size2, fd ) ;
}

int xbox_sopen( char *name, char* type )
{
	return g_app->m_smb.open( name,O_RDONLY|O_BINARY);
}

int xbox_sclose( int fd )
{
	return g_app->m_smb.close( fd );
}

int xbox_sseek( int fd, int pos, int type )
{
	//sprintfx( "seek %d %d %d\r\n", fd, pos, type ) ;
	return g_app->m_smb.lseek( fd, pos, type ) ;
	//sprintfx( "seeke %d %d %d\r\n", fd, pos, type ) ;
}


int xbox_rread( void *buf, int size1, int size2, void *fd )
{

	//sprintfx( "read %u %u %d\r\n", size1, size2, fd ) ;
	if ( ((CRelax*)fd)->ReadAll( buf, size1*size2 ) )
		return size1*size2 ;
	else
		return 0 ;

	//sprintfx( "reade %u %u %d\r\n", size1, size2, fd ) ;
}

void* xbox_ropen( char *name, char* type, int tracknum )
{
	if ( g_app->m_relaxTracks[tracknum].Open( name ) )
	{
		//sprintfx( "ptr %d = track %u\r\n", &(g_app->m_relaxTracks[tracknum]), tracknum ) ;
		return &(g_app->m_relaxTracks[tracknum]) ;
	}
	else
		return NULL ;
}
unsigned int xbox_rlength( void *fd )
{
	return ((CRelax*)fd)->GetLength() ;
}

int xbox_rclose( void *fd )
{
	((CRelax*)fd)->Close() ;
	return 1 ;
}

int xbox_rseek( void *fd, int pos, int type )
{
	//sprintfx( "seek %d %d %d\r\n", fd, pos, type ) ;
	((CRelax*)fd)->Seek( pos, type ) ;
	return pos ;
}

int xbox_check_events()
{
	//writexbox( "before events") ;
	return g_app->handleEvents() ;
	//writexbox( "after events") ;
	return 0 ;
}

void xbox_process_audio()
{
	g_sound->process() ;
	g_cdda->process() ;
	g_mp3player->process() ;

	g_app->m_numFrames++ ;
}

void xbox_put_image()
{
	//writexbox( "before render") ;
	//g_sound->process() ;
	//g_mp3player->process() ;
	g_app->render_to_texture() ;
	//writexbox( "after render") ;
}

void xbox_open_zip( char *hugozipfile )
{
	//writexbox( "before zip") ;
	//g_app->rom_load_zip( hugozipfile ) ;
	//writexbox( "after zip") ;
}

#ifdef __cplusplus
}
#endif

void CXBoxSample::processEmu( BOOL render )
{
			
			handleEvents();
			updateCheats() ;


//			doneFrame = 0 ;

			//m_nbytes = update_sound_main() ;



			if ( render )
			{
				//render_to_texture();
				m_numFrames++ ;
			}


//			m_droppedFrames += m_sound.process( (byte**)sbuf, m_nbytes, soundChannels ) ;

			while ( m_sound.m_bDanger )
			{
				handleEvents();
				updateCheats() ;
//				doneFrame = 0 ;
				//m_nbytes = update_sound_main() ;


				//m_droppedFrames += m_sound.process( (byte**)sbuf, m_nbytes, soundChannels ) ;
			}



}


int CXBoxSample::rom_load_zip( char *hugozipfile )
{
	return 1;
}

