#define SHOWFPS
#define CHECKAVAILROMS
#define CHECKRUMBLECHEATS
#define CHECKGAMESCREENSIZE
#define NATIVEASPECT
#define BOOTXBOX
#define FLOATSTICK
#define STATEMEM_SIZE 0x10000
#define KEYBOARDMENU 0
#define EMU_VERSION 19
#define CHECKED_RESET_SOFTEN
#define SHOWFPS
#define NEWSAVEPOS2
#define RELAXCASE
#define CHEAT5000
#define LIGHTGUN 1
#define FRSPRITES
#define XBOX_COMPAT_NAME
#define SAVE_SCREENSTATE
#define CHECKED_RESET_FLICKER
#define HARDFILTER_APPLY
#define NO_EXTRA_ZIP
//#define USE_DEBUGCLIENT
//#define NO_CONFIGURATION

char *ASPECT_RATIO_NAMES[] = { "None", "Best-NES-TV", "NES-Native" } ;
float ASPECT_RATIOS[] = { 1.0f, 320.0f/240.0f, 320.0f/224.0f } ;
#define NUM_ASPECT_RATIOS 3
#define DEFAULT_PATTERN_X 320
#define DEFAULT_PATTERN_Y 240

#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 "numpadg.h"
#include "png.h"
//#include "SDL.h"
#include "disksys.h"
#include "keyboard_api.h"
#include "gamescreen.h"

#ifdef LIGHTGUN
#include "lightgun.h"
#endif


#ifdef __cplusplus
extern "C" {
#endif

#include "types.h"
#include "video.h"
#include "fce.h"
#include "svga.h"
#include "sound.h"
#include "state.h"
#include "fds.h"

void FCEUI_SetSoundQuality(int quality);

#include "writepng.h"

void SpeedThrottle(void) ;
void InitSpeedThrottle(void);

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, ... );
//extern int iFastFwd ;
//int LoadState(char *file) ;
//int SaveState(char *file) ;
//extern int Running;
//int psx_WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) ;

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

#ifdef __cplusplus
}
#endif

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

#define PLATFORM_NAME "NES"
#define PLATFORM_SAV L"NESSAV"
#define READING_ROMS_STRING L"Reading nesroms directory...please wait."
#define PLATFORM_INI "fceu.ini"
#define PLAYTHING_INI "plaything.cfg"
#define PLATFORM_MEMORY_POINTER RAM
#define THEMEMUSIC "D:\\NESTHEME.MP3"
#define PLATFORM_FILE_DIR m_defaultRomDir
#define DEFAULT_PARENT_DIR "D:\\nesroms\\*"
#define CD_BUF_SECTORS 1
#define CD_DATA_BUFFER_SIZE CD_BUF_SECTORS*2352
#define PROJECTILE_DEF 4 
#define DEFAULT_SKIN "default_fceultra"
#define DEFAULT_SKIN_DIR "D:\\EMUSKINS"
#define MAIN_MENU_STRING L"FceUltraX Main Menu"
#define MLINE 
#define DEFAULT_SAVE_PATH "E:\\SAVES\\FCEULTRA"
#define GAME_GENIE 1
#define EMU_RECORDING_SIZE ( sizeof(DWORD)*4*60*60*10 )

int CODE_LENGTHS[] = { 12 } ;

#define CONSOLE_MEMORY_SIZE 0x800
unsigned char *m_memory_locations[] = { RAM  } ;
unsigned int  m_memory_sizes[] = { 0x800 } ;
#define NUM_MEMORY_LOCATIONS 1

byte keyboard_keystate[256] ;

typedef struct
{

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

typedef struct
{
	float        stick_sensitivity ;
	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 ;
	unsigned int virtual_keyboard ;
	unsigned int text_browser ;
	unsigned int toggle_rewind ;
	unsigned int toggle_slowdown ;
	unsigned int rewind ;
	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 ;
	int  transition ;

	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   1
#define JOY_B   2
#define JOY_SELECT      4
#define JOY_START       8
#define JOY_UP  0x10
#define JOY_DOWN        0x20
#define JOY_LEFT        0x40
#define JOY_RIGHT       0x80
*/
#define INSERT_FDS 0x100
#define CHANGE_FDS 0x200


	BUTTON_DEFINITION g_emuButtonDefinitions[] = {
		{ "A", JOY_A },
		{ "B", JOY_B },
		{ "Up", JOY_UP },
		{ "Down", JOY_DOWN },
		{ "Left", JOY_LEFT },
		{ "Right", JOY_RIGHT },
		{ "Start", JOY_START },
		{ "Select", JOY_SELECT },
		{ "Insert/Eject FDS", INSERT_FDS },
		{ "Change FDS", CHANGE_FDS },
		{ "Nothing", 0 },
	} ;

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


#define DEFAULT_BUTTON1  XBOX_A
#define DEFAULT_BUTTON2  XBOX_X
#define DEFAULT_BUTTON3  XBOX_DPAD_UP
#define DEFAULT_BUTTON4  XBOX_DPAD_DOWN
#define DEFAULT_BUTTON5  XBOX_DPAD_LEFT
#define DEFAULT_BUTTON6  XBOX_DPAD_RIGHT
#define DEFAULT_BUTTON7  XBOX_START
#define DEFAULT_BUTTON8  XBOX_BACK
#define DEFAULT_BUTTON9  XBOX_Y
#define DEFAULT_BUTTON10 XBOX_B
#define DEFAULT_BUTTON11 0
#define DEFAULT_BUTTON12 0
#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, int forceConfig ) ;
	virtual void    cleanupConsole( ) ;
	virtual void    handleEvents() ;
	virtual int     init_texture() ;
	virtual void    copyOldSaves() ;
	virtual BOOL    SetRefreshRate(INT iRefreshRate);
	virtual int		init_white_texture();
	void            loadMostRecentSaveState( ) ;
	virtual int		render_to_texture() ;
	virtual void	FindAvailRoms(char *dir) ;
	void            renderMenuText( int selectable, int selected, WCHAR **lines, int numlines, int isPopup, int firstisfirst, int lastislast ) ;
	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    doChangeHWFilter() ;
	virtual void    applyGameGenie( byte *ROM, unsigned int romsize);
	virtual void    doChangeSWFilter() ;
#ifdef LIGHTGUN
	virtual void    doZapper();
	virtual void    doCalibrateLightgun( bool changeValues ) ;
	virtual void    doConfigureLightgun() ;
#endif
	virtual void    doPlaythingClear( );
	virtual void    saveSettings( char *filename );
	virtual int     loadSettings( char *filename );
	virtual void    doAutofireConfig( int port );
	virtual void    doMainMenu() ;
	virtual int     encodeGameGenie( CHEAT_CODE *code ) ;
	virtual int     decodeGameGenie( CHEAT_CODE *code ) ;
	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    doBrowseScreenshots( ) ;
	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	viewCheatMatches();
	virtual void	viewMemoryDump( unsigned int offset );
	virtual void	doRumbleConfigSelect( int port );
	virtual void	doRumbleConfig( void *rumble );
	virtual int     handleExtension( char *ext, char *zipfile, char *newfilename, int *zipnumber );
	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, int forceConfig ) ;
	virtual void    getNewRoot( char *szRoot) ;
	unsigned int    getNewDefinition( unsigned int oldMapping );
	unsigned int    doSelectGame( int onlyFavorites, int canChangeDir, int getPath=0 ) ;
	virtual void    SetupPlaything( );
	virtual void    xboxStartRecording() ;
	virtual void    xboxStopRecording() ;
	virtual void    xboxStartPlaying() ;
	virtual void    xboxStopPlaying() ;
	virtual void    xboxOptionsMenu() ;
	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    doSavePlaything() ;
	virtual int     setupNetplay() ;
	virtual void    doLoadPlaything() ;
	virtual void    ColorBar( int xpos, int ypos, int xlen, int ylen, DWORD color );
	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    doConfigureGame( char *settingsname, char *keysname ) ;
	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 ) ;
	void            doAddGamesharkCodes( char *filepos, char *codedesc);
	void            doShowGamesharkCodes( int which);
	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    updateEmuSpecificCheats( ) ;
	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    doEditGameGenie( int selected ) ;
	virtual void    doFontSize() ;
	virtual void    xboxSaveState() ;
	virtual void    xboxThrottle( int throttle ) ;
	virtual void    xboxLoadState() ;
	void            doSelectTransition( );
	void            doChangeVideoMode( );
	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	viewTextFile( char *filename ) ;
	virtual void    doScreenSize( int ivar ) ;
	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 void	doSettings2();
	virtual void	editPlaylist( char *filename );
	virtual void	managePlaylists( );
	virtual void	viewPlaylist( );
	virtual int		selectFile( char *filename, char *dirname, int canchangedir, int selectdir, int refreshlist, int initlist  );
	virtual void	applyHardwareFilter( ) ;
	virtual int     selectNetplayServer() ;
	virtual void    doTextOffset() ;
	void            renderScreenKeyboard( );
	virtual void    getKeyboardString( char *buf, int bufsize ) ;
	void            musicControlMenu( CPanel *panel );
	void            doDefaultDirs();
	virtual	void	createLocal( char *filename, char *newfilename, char* zipfilename, int *zipnumber );
	virtual int     addGameGenieCode() ;
	void            ClearScreen() ;
	virtual void    doConfiguration() ;
	virtual void    updateCheats() ;
	virtual void    updateCheats2() ;
	void            doSwapDrive();
	virtual void    processEmu( BOOL render ) ;
	virtual void    fillPresentationParams() ;
	virtual void    cht_load() ;
	virtual void    cht_save() ;
	virtual void    doUtilities( );
	virtual void    doHelp( );
	virtual void    doSettings( );
	virtual void    doCheatCodes( );
	virtual void    doGameUtilities( );
	virtual int     selectState( );
	virtual void    deleteSaveFiles( int which, int onlyFavorites ) ;
	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 ) ;
	virtual void    GetPalette(uint8 i, uint8 *r, uint8 *g, uint8 *b);
	virtual void    SetPalette(uint8 index, uint8 r, uint8 g, uint8 b);

	

	int m_changedGenie ;
	int m_refreshRate ;
	int m_clipSides ;
	DWORD m_joypad ;
	int m_forceFaster ;
	DWORD m_zapperDat[3] ;
	D3DCOLOR			color_palette[256];
	int                 PaletteChanged ;	
	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 ;

	D3DXVECTOR2 m_gameVecScale ; 
	D3DXVECTOR2 m_gameVecTranslate ; 
	RECT m_gameRectSource ;
	int m_throttle ;

	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 ;
	int  m_scrollSpeed ; 
	int   keyTime ;
	unsigned int m_pitch ;
	DWORD  m_bRealCD ;
	DWORD  m_currentStartSector ;
	unsigned char *m_ptrCdBuf ;
	char m_cdromID[11]; 
	DWORD m_bitDepth ;
	DWORD m_lineHeight ;
	unsigned int m_zapperNum ;
	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 ;

	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 ;
	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	WhiteTexture;
	LPD3DXSPRITE			Sprite;
	LPD3DXSPRITE			MenuSprite;
	byte*				g_pBlitBuff ;
	byte*				g_pUnpaletteBuff ;
	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;
    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 ;


	char *m_cheatfile ;
	unsigned int m_numDBCheats ;

	UINT32 m_numCheats ;


};


#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_zapperNum = GetIniInt( szbuf, "EMU_SPECIFIC", "zapper_num", 0 ) ;
}

void CXBoxSample::doSaveEmuSpecificIni( FILE *outfile ) 
{


	//fprintf( outfile, "[EMU_SPECIFIC]\r\n" ) ;
	//fprintf( outfile, "zapper_num=%u\r\n", m_zapperNum ) ;
	//fprintf( outfile, "\r\n" ) ;


}

int CXBoxSample::handleExtension( char *ext, char *zipfile, char *newfilename, int *zipnumber )
{
	return 0 ;
}

int CXBoxSample::init_texture()
{
	D3DCOLOR *palette ;

	// Release any previous texture
	if (Texture) 
	{ 
		m_pd3dDevice->CreatePalette( D3DPALETTE_256 , &m_pd3dPalette ) ;
		m_pd3dPalette->Lock( &palette, 0 ) ;
		memset( palette, 44, 256* sizeof( D3DCOLOR ) ) ;
		m_pd3dPalette->Unlock() ;

		m_pd3dDevice->SetPalette( 0, m_pd3dPalette ) ;
		XBuf = g_pBlitBuff ;
		return 1 ;
		Texture->Release();
		Texture = NULL;
	}
	
	theWidth = 512 ;
	theHeight = 480 ;


	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 ) ;
	}
	
	
	
	// Create the texture
	
	//D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_R5G6B5, D3DPOOL_DEFAULT, &Texture);
//	D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_P8, D3DPOOL_DEFAULT, &Texture);
//	D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &Texture);
//	D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_DEFAULT, &Texture);
	
	D3DSURFACE_DESC desc;
    Texture->GetLevelDesc(0, &desc);

	sprintfx( "before inittex\r\n") ;

	xbox_print_memory() ;
	
	if (g_pBlitBuff != NULL)
	{
		delete [] g_pBlitBuff;
		g_pBlitBuff = NULL;
	}
	
	// Allocate a buffer to blit our frames to
	g_pBlitBuff = new byte[ (256+32) * (240+32) ];

	XBuf = g_pBlitBuff ;

	xbox_print_memory() ;

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

	xbox_print_memory() ;

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

	//xbox_print_memory() ;

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

	//xbox_print_memory() ;

	if ( g_pDeltaBuff == NULL )
		return 1 ;

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

	sprintfx( "aft inittex\r\n") ;
	

	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);

	m_pd3dDevice->CreatePalette( D3DPALETTE_256 , &m_pd3dPalette ) ;
	m_pd3dPalette->Lock( &palette, 0 ) ;
	memset( palette, 44, 256* sizeof( D3DCOLOR ) ) ;
	m_pd3dPalette->Unlock() ;

	m_pd3dDevice->SetPalette( 0, m_pd3dPalette ) ;

	return 0;
}












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

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

	bool musicPlaying ;

	musicPlaying = !m_mp3player.m_bPaused ;

	initConsole(gameSelected, isFavorite, forceConfig) ;

	sprintfx( "before free\r\n") ;
	freeTextures() ;
	sprintfx( "after free\r\n") ;

	while ( m_state == IN_GAME )
	{
		//sprintfx( "procemu\r\n") ;
		processEmu(TRUE) ;
	}

	saveKeys( g_keysfile ) ;
	cleanupConsole() ;
	m_sound.cleanup() ;
	m_state = MAIN_MENU ;
	m_sockNetplay.m_debugClientSock.Close() ;

	freeTextures() ;

	if ( g_autoLaunchGame )
	{
		changeMenu( &m_skin.otherMenu, &m_skin.mainMenu ) ;
	}
	else
	{
		changeMenu( &m_skin.otherMenu, &m_skin.gameSelectMenu ) ;
	}

	if ( musicPlaying )
	{
		m_mp3player.pause( FALSE ) ;
	}

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

}





void CXBoxSample::GetPalette(uint8 i, uint8 *r, uint8 *g, uint8 *b)
{
	*r=( color_palette[i] >> 16 ) & 0xFF ;
	*g=( color_palette[i] >> 8 ) & 0xFF ;
	*b=( color_palette[i]  ) & 0xFF ;
}

void CXBoxSample::SetPalette(uint8 index, uint8 r, uint8 g, uint8 b)
{

	color_palette[index] = ( 0xFF << 24 ) | ( r << 16 ) | ( g << 8 ) | (b)  ;
	PaletteChanged=1;
}



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

	m_changedSettings = 0 ;

	setfile = fopen( filename, "wb" ) ;

	if ( !setfile )
		return ;


	fwrite( &m_zapperNum, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_refreshRate, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_clipSides, sizeof(unsigned int), 1, setfile ) ;

	fclose( setfile ) ;

}

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

	m_changedSettings = 0 ;

	setfile = fopen( filename, "rb" ) ;

	m_zapperNum = 0 ;
	m_refreshRate = 0 ;
	m_clipSides = 0 ;

	if ( !setfile )
	{
		saveSettings( filename ) ;
		return 1;
	}


	fread( &m_zapperNum, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_refreshRate, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_clipSides, sizeof(unsigned int), 1, setfile ) ;

	fclose( setfile ) ;
	
	if ( ( m_xboxSFilter < 0 ) || ( m_xboxSFilter >= NUM_SOFTWARE_FILTERS ))
	{
		m_xboxSFilter = 0 ;

	}

	return 0 ;
}






struct genietable
{
	byte nibble ;
	char code ;
} GENIETABLE[] = 
{
	{ 0x0, 'A' },
	{ 0x1, 'E' },
	{ 0x2, 'P' },
	{ 0x3, 'O' },
	{ 0x4, 'Z' },
	{ 0x5, 'X' },
	{ 0x6, 'L' },
	{ 0x7, 'U' },
	{ 0x8, 'G' },
	{ 0x9, 'K' },
	{ 0xA, 'I' },
	{ 0xB, 'S' },
	{ 0xC, 'T' },
	{ 0xD, 'V' },
	{ 0xE, 'Y' },
	{ 0xF, 'N' }
} ;

int CXBoxSample::encodeGameGenie( CHEAT_CODE *code ) 
{
	DWORD encodedVal ;
	int codesize ;
	byte andVal ;
	byte shiftval ;
	byte codeofs ;
	byte highbit ;

	codesize = 6 ;

	code->adr &= 0xFFFF ;
	code->val &=0xFF ;

	encodedVal = ( ( code->adr & 0xF000 ) >> 4 ) |
				 ( ( code->adr & 0x0F00 ) >> 8 ) |
				 ( ( code->adr & 0x00F0 ) << 8 ) |
				 ( ( code->adr & 0x000F ) << 4 ) |
				 ( ( code->val & 0x00F0 ) << 12 ) |
				 ( ( code->val & 0x000F ) << 20 )  ;


	if ( code->type == 0x98 ) //8 char code
	{
		codesize = 8 ;

		encodedVal |= 0x800 ; //8 char codes must have high bit of adr set to 1

		encodedVal = encodedVal << 8 ;
		encodedVal = encodedVal |
				 ( ( code->code[16] & 0x00F0 ) >> 4 ) |
				 ( ( code->code[16] & 0x000F ) << 4 )  ;

		highbit = ( encodedVal & 0x80000000 ) >> 31;
	}
	else
	{
		encodedVal &= ~0x800 ; //6 char codes must have high bit of adr set to 0
		highbit = ( encodedVal & 0x800000 ) >> 23;
	}

	encodedVal = (encodedVal << 1) | highbit;

	andVal = 0xF ;
	shiftval = 0 ;

	if ( codesize == 6 )
		codeofs = 2 ;

	for ( int i = codesize-1 ; i >= 0 ; i-- )
	{
		code->code[i] = GENIETABLE[ ( ( encodedVal & andVal ) >> shiftval ) & 0xF ].code ;
		andVal = andVal << 4 ;
		shiftval += 4 ;

	}

	code->code[codesize] = 0 ;

	return 0 ;
}

int CXBoxSample::decodeGameGenie( CHEAT_CODE *code ) 
{
	DWORD encodedVal ;
	int codesize ;
	byte andVal ;
	byte shiftval ;
	byte codeofs ;
	byte nibble;
	DWORD highbit ;

	codesize = strlen( code->code ) ;
	strupr( code->code ) ;


	encodedVal = 0 ;
	shiftval = 0 ;

	for ( int i = codesize-1 ; i >= 0 ; i-- )
	{
		for ( int j = 0 ; j < 16 ; j++ )
		{
			if ( code->code[i] == GENIETABLE[j].code ) 
			{
				nibble = GENIETABLE[j].nibble ;
				break ; 
			}
		}

		encodedVal |= ( nibble << shiftval ) ;
		shiftval += 4 ;

	}


	if ( codesize == 8 )
	{
		highbit = ( encodedVal & 0x01 ) << 31 ;
	}
	else
	{
		highbit = ( encodedVal & 0x01 ) << 23 ;
	}

	encodedVal = encodedVal >> 1 ;

	encodedVal &= 0x7FFFFFFF ;

	encodedVal |= highbit ;

	if ( codesize == 8 )
	{
		code->type = 0x98 ;
		code->code[16] = ( ( encodedVal & 0x0F ) << 4 ) |
						 ( ( encodedVal & 0xF0 ) >> 4 ) ;
		encodedVal = encodedVal >> 8 ;
	}
	else
	{
		code->type = 0x99 ;
	}



	code->adr = ( ( encodedVal & 0x0F00 ) << 4 ) |
				( ( encodedVal & 0x000F ) << 8 ) |
				( ( encodedVal & 0xF000 ) >> 8 ) |
				( ( encodedVal & 0x00F0 ) >> 4 )  ;

	code->val = ( ( encodedVal & 0x0F0000 ) >> 12 ) |
				( ( encodedVal & 0xF00000 ) >> 20 ) ;

	code->desc[0] = 0 ;

	if ( code->adr >= 0x8000 )
		code->adr -= 0x8000 ;

	return 0 ;
}

int CXBoxSample::addGameGenieCode()
{
	int value ;
	int menuChoice = 0 ;
	int numitems ;

	value = 0 ;


	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu);

	
		swprintf( m_menuText[0], L"Add Game Genie Code"  );
		swprintf( m_menuText[1], L"Add 6-Char Code");
		swprintf( m_menuText[2], L"Add 8-Char Code");

		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 3, 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();
			return 1  ;
		}
		else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
		{
			m_sfxMenuSelect.Play( DSBPLAY_FROMSTART ) ;

			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) ) ;

			code.type = menuChoice == 0 ? 0x99 : 0x98 ;

			encodeGameGenie( &code ) ;

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

			memcpy( &(m_cheatCodes[m_numCheats]),&code, sizeof(CHEAT_CODE) ) ;
			memset( &(g_rumbleCodes[m_numCheats]),0, sizeof(RUMBLE_CODE) ) ;

			m_numCheats++ ;

			return 0 ;
		}
	}

	return 1 ;
}


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 ;
	}


	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( NUMPADG_PNG, sizeof(char), sizeof(NUMPADG_PNG), outfile ) ;
	fclose( outfile ) ;



	pmenuParams = &(m_skin.otherMenu) ;
	
	if (D3DXCreateTextureFromFileEx(m_pd3dDevice, "X:\\NUMPADG.PNG",
		 NUMPADG_WIDTH, NUMPADG_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, NUMPADG_WIDTH, NUMPADG_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 ;

	if ( m_cheatCodes[selected].type == 0x98 )
	{
		numpositions = 8 ;
	}
	else
	{
		numpositions = 6 ;
	}

	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);


	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_WIDTH)/2 ;
	panely = 82 ; 

	while ( 1 )
	{

		pmenuParams = &(m_skin.otherMenu) ;

		m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
							0x00000000, 1.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_WIDTH, NUMPAD_HEIGHT ) ;


		m_mp3player.process() ;


		D3DXVECTOR2 vecScale( 1, 1 ) ;
		D3DXVECTOR2 vecTranslate( panelx + 4 + ( 53 * ( numpad % 4 )), panely + 4 + ( 53 * ( numpad / 4 ) ) ) ;
		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_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] = 'A' ; break ; 
				case 1 : truncCode[pos] = 'E' ; break ; 
				case 2 : truncCode[pos] = 'G' ; break ; 
				case 3 : truncCode[pos] = 'I' ; break ; 
				case 4 : truncCode[pos] = 'K' ; break ; 
				case 5 : truncCode[pos] = 'L' ; break ; 
				case 6 : truncCode[pos] = 'N' ; break ; 
				case 7 : truncCode[pos] = 'O' ; break ; 
				case 8 : truncCode[pos] = 'P' ; break ; 
				case 9 : truncCode[pos] = 'S' ; break ; 
				case 10 : truncCode[pos] = 'T' ; break ; 
				case 11 : truncCode[pos] = 'U' ; break ; 
				case 12 : truncCode[pos] = 'V' ; break ; 
				case 13 : truncCode[pos] = 'X' ; break ; 
				case 14 : truncCode[pos] = 'Y' ; break ; 
				case 15 : truncCode[pos] = 'Z' ; 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 %4 ) == 3 )
				numpad -= 3 ;
			else
				numpad++ ;

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

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

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

		}
		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 ) ;

			if ( ! decodeGameGenie( &editedCode ) )
			{
				memcpy( &(m_cheatCodes[selected]), &editedCode, sizeof(CHEAT_CODE) ) ;
				m_changedGenie = 1 ;
				break ;
			}
			else
			{
				popupMsg( "The code you entered is invalid.", &m_pnlBackgroundOther ) ;
			}
		}
	}

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

}



void CXBoxSample::updateEmuSpecificCheats( ) 
{
}


int CXBoxSample::addEmuSpecificOptions( int start )
{
	return start ;

		//swprintf( m_menuText[start], L"Search Gameshark Database for Codes");
		//swprintf( m_menuText[start+1], L"Load new disc image");

		//return start+2 ;

}

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

}

void CXBoxSample::performEmuSpecificOption( int start, int menuChoice ) 
{
	if ( menuChoice == start )
	{
//		doSearchGameshark() ;
	}
	else if ( menuChoice == start+1 )
	{
//		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 ;
}









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

	InitializeWithScreen() ;
    return S_OK;
}


int CXBoxSample::render_to_texture()
{
	RECT src, dst;
	WORD *curr1 ; 
	byte *curr2 ;
	DWORD pitchDiff ; 
	D3DCOLOR *palette ;
	char palstr[200] ;
	DWORD pixel ;
	byte r,g,b ;
	int realWidth ;

	if ( PaletteChanged != 0 )
	{
		m_pd3dDevice->GetPalette( 0, &m_pd3dPalette ) ;
		m_pd3dPalette->Lock( &palette, 0 ) ;
		memcpy( palette, color_palette, 256* sizeof( D3DCOLOR ) ) ;
		m_pd3dPalette->Unlock() ;
		PaletteChanged = 0 ;
	}

	//sprintfx("rendertext\r\n") ;

	// 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);
	
	
	// Allocate a buffer to blit our frames to

	// Figure out how big of a rect to lock in our texture
	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);

	
	if ( m_xboxSFilter )
	{
		curr1 = (WORD*)g_pUnpaletteBuff ;
	}
	else
	{
		curr1 = (WORD*)d3dlr.pBits;
	}


	int totallines=FSettings.LastSLine-FSettings.FirstSLine+1;

	realWidth = m_clipSides ? 240 : 256 ;

	//tmp=XBuf+8+FSettings.FirstSLine*272;
	
	curr2 = g_pBlitBuff + 8 + ( 272 * FSettings.FirstSLine ) ;

	if ( m_clipSides )
		curr2 += 8 ;

	pitchDiff = ( m_pitch - 512 ) / 2 ;


	for ( int y = 0 ; y < totallines ; y++ )
	{
		for ( int x = 0 ; x < realWidth; x++ )
		{
			pixel = color_palette[*curr2++] ;
			r = ( ( pixel >> 16 ) & 0xFF ) >> 3 ;
			g = ( ( pixel >> 8 ) & 0xFF ) >> 2 ;
			b = ( ( pixel  ) & 0xFF ) >> 3;

			*curr1++ = ( r << 11 ) | ( g << 5 ) | ( b ) ;
		}

		if ( m_clipSides )
		{
			curr2 += 32 ;
			curr1 += pitchDiff + 16;
		}
		else
		{
			curr2 += 16 ;
			curr1 += pitchDiff ;
		}

	}









	float mx, my ;

	if ( m_xboxSFilter )
	{
		SOFTWARE_FILTERS[m_xboxSFilter].blitfunc(g_pUnpaletteBuff+m_pitch, m_pitch, g_pDeltaBuff+m_pitch, (unsigned char*)d3dlr.pBits, m_pitch, realWidth, totallines, 0 ) ;
		//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
		Texture->UnlockRect(0);
		g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
		g_pd3dDevice->BeginScene();

		//memcpy( g_pDeltaBuff, g_pUnpaletteBuff, 240*512 ) ;
		mx = (float)m_nScreenMaxX / ((float)(realWidth)*2.0f) ;
		my = (float)m_nScreenMaxY / ((float)(totallines)*2.0f);

		m_gameRectSource.top = 0;
		m_gameRectSource.left = 0;
		m_gameRectSource.bottom = ((totallines) )*2 ;
		m_gameRectSource.right  = (realWidth )*2;
	}
	else
	{
		//memcpy( d3dlr.pBits, g_pUnpaletteBuff, desc.Size ) ;
		//XGSwizzleRect(g_pUnpaletteBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
		Texture->UnlockRect(0);
		g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
		g_pd3dDevice->BeginScene();

		mx = (float)m_nScreenMaxX / ((float)realWidth) ;
		my = (float)m_nScreenMaxY / ((float)(totallines));

		m_gameRectSource.top = 0;
		m_gameRectSource.left = 0;
		m_gameRectSource.bottom = ((totallines) ) ;
		m_gameRectSource.right  = (realWidth );
	}

	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( m_gameRectSource.left, m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;

	//Sprite->Draw(Texture, &m_gameRectSource, &m_gameVecScale, NULL, 0, &m_gameVecTranslate, d3color);

	if ( g_bShowFPS )
	{
		sprintf( global_error_message, "fps=%.1f", (float)m_numFrames*1000.0/((float)(GetTickCount() - g_dwStartTime)) );
		m_msgDelay = 3 ;

		if ( GetTickCount() - g_dwStartTime > 1000 )
		{
			g_dwStartTime = GetTickCount() ;
			m_numFrames = 0 ;
		}
	}
	if ( global_error_message[0] )
	{
		if ( m_msgDelay > 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   ) ;
		}
	}
#ifdef LIGHTGUN
	if ( m_zapperNum && m_lightgunTarget )
	{
		if ( m_lightgun.wButtons & XINPUT_LIGHTGUN_ONSCREEN  )
		{
			FLOAT fWidth = 640.0f *VIDEOMODES[m_xboxVidmode].multx;
			FLOAT fHeight = 480.0f *VIDEOMODES[m_xboxVidmode].multy;
			FLOAT fThumbLX = (fWidth/2) + (fWidth/2)*(m_lightgun.sThumbLX+0.5f)/32767.5f;
			FLOAT fThumbLY = (fHeight/2) - (fHeight/2)*(m_lightgun.sThumbLY+0.5f)/32767.5f;
		    //ColorBar( fThumbLX-10, fThumbLY-10, 20,20, 0xFF00FF00 );
			ColorBar( fThumbLX-1, fThumbLY-8, 2, 16, 0xffff0000);
			ColorBar( fThumbLX-8, fThumbLY-1, 16, 2, 0xffff0000);
		}
	}
#endif
	// End the scene.
	g_pd3dDevice->EndScene();
	
	//if ( ( !m_throttle ) && ( !m_forceFaster ) && ( ! m_sound.m_bDanger ) )
		//g_pd3dDevice->BlockUntilVerticalBlank() ;

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


/*
	float FPS, desiredFPS ;

	//desiredFPS = 60.5f ;
	desiredFPS = m_refreshRate ;

	if ( m_throttle )
		desiredFPS = desiredFPS * 3.0f ;


	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 %.1f\r\n", FPS, desiredFPS);
			//m_msgDelay = 20 ;
		}
		else
		{
			FPS = 100.0f ;
			//sprintf( global_error_message, "fps=too much...\r\n");
			//m_msgDelay = 20 ;
		}

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

	m_performancePrev[0] = m_performanceCurr[0];



*/

	return 1;
	
	// Swizzle the blittled surface back to the texture
	//XGSwizzleRect(g_pAlignBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 1);


	// Swizzle the blittled surface back to the texture
//	XGSwizzleRect(XBuf+8, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 1);
	//XGSwizzleRect(g_pBlitBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 4);
/*
	// Unlock our texture
	Texture->UnlockRect(0);

	//delete [] g_pBlitBuff;
	//g_pBlitBuff = NULL;


	src.left   = 0;
	src.top    = 0;
	src.right  = theWidth  + 0;
	src.bottom = theHeight + 1;

	UINT iWidth  = theWidth;
	UINT iHeight = theHeight;
	
	// win_start_maximized the rect, constraining to the aspect ratio
	dst.left   = dst.top = 0;
	dst.right  = iWidth;
	dst.bottom = iHeight;
	
	// center
	//dst.left   += ((iWidth - (dst.right - dst.left)) / 2)  + ((640-iWidth)/2);
	//dst.top    += ((iHeight - (dst.bottom - dst.top)) / 2) + ((480-iHeight)/2);
	//dst.right  += dst.left;
	//dst.bottom += dst.top;
	
    // Clear the viewport
//	if ( ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_A ] ) || ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_X ] ) )  
	    g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
	
	// Begin the Scene
	g_pd3dDevice->BeginScene();

	// Compute the source and dest image sizes
	const float dw = dst.right-dst.left;
	const float dh = dst.bottom-dst.top;
	const float sw = src.right-src.left;
	const float sh = src.bottom-src.top;


	float mx, my ;

	mx = (float)m_nScreenMaxX / (float)theWidth ;
	my = (float)m_nScreenMaxY / (float)theHeight ;

	// Compute the scale and transform vectors
	//D3DXVECTOR2 vecScale(dw/sw, dh/sh);
	D3DXVECTOR2 vecScale(mx, my);
	D3DXVECTOR2 vecTranslate(m_nScreenX, m_nScreenY );


	// Compute the scale and transform vectors
	//D3DXVECTOR2 vecScale(dw/sw, dh/sh);
	//D3DXVECTOR2 vecScale(2, 2);
	//D3DXVECTOR2 vecTranslate(56, 0 );
	//D3DXVECTOR2 vecTranslate(dst.left, dst.top);
	
	D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0);
	
	// Draw the sprite
	//if ( ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_A ] ) || ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_Y ] ) )  
		Sprite->Draw(Texture, &rectSource, &vecScale, NULL, 0, &vecTranslate, d3color);
	
	if ( global_error_message[0] )
	{
		if ( m_msgDelay > 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   ) ;
		}
	}

	// End the scene.
	g_pd3dDevice->EndScene();
	
	// Present the scene
	//if ( ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_A ] ) || ( m_DefaultGamepad.bAnalogButtons[ XINPUT_GAMEPAD_BLACK ] ) )  
		g_pd3dDevice->Present(NULL, NULL, NULL, NULL);

	return 1;
	*/
}

void CXBoxSample::InitializeEmuSpecific()
{

	g_pUnpaletteBuff = NULL ;
	m_refreshRate = 60 ;
	m_clipSides = 0 ;

	FILE *outfile ;

	outfile = fopen( "X:\\DISKSYS.ROM", "wb") ;
	
	if ( outfile )
	{
		fwrite( DISKSYS_ROM, sizeof(char), 8192, outfile ) ;
		fclose(outfile) ;
	}

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

//	LoadCheatDB() ;



}


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


    return S_OK;
}





#ifdef LIGHTGUN

void CXBoxSample::doZapper()
{
	BOOL bShotFired;
	BOOL bShotHitScreen;
	BOOL bShotMissedScreen;
	int foundgun = 0 ;

	// Check all ports for a lightgun
	for( DWORD i=0; i<4; i++ )
	{
		if( g_Gamepads[i].hDevice && g_Gamepads[i].caps.SubType == XINPUT_DEVSUBTYPE_GC_LIGHTGUN )
		{
			// Copy the gamepad input to the lightgun structure.
			// Note: This is just for convenience so we can refer to a 
			// "lightgun" instead of a "gamepad".
			m_lightgun.CopyInput( &g_Gamepads[i], i );
			foundgun = 1 ;
			break ;

		}
	}

	if ( foundgun == 0 )
	{
		return ;
	}

	//m_lightgun.DisplayWhiteField() ;

	// Make sure the gun is properly calibrated. Note that this is called every
	// frame in case the state of the display changes
	m_lightgun.VerifyCalibrationState( FALSE );

	// Set the vibration motors
	//m_Lightgun.SetVibrationMotors( m_wLeftMotorSpeed, m_wRightMotorSpeed );


	m_lightgun.Update( &bShotFired, &bShotHitScreen, &bShotMissedScreen );

	m_zapperDat[2] = 0 ;

	if ( bShotFired )
	{
		m_zapperDat[2] |= 1 ;
		if ( bShotMissedScreen )
		{
			m_zapperDat[2] |= 2 ;
		}
	}

	FLOAT fWidth = 640.0f *VIDEOMODES[m_xboxVidmode].multx;
	FLOAT fHeight = 480.0f *VIDEOMODES[m_xboxVidmode].multy;
    FLOAT fThumbLX = (fWidth/2) + (fWidth/2)*(m_lightgun.sThumbLX+0.5f)/32767.5f;
    FLOAT fThumbLY = (fHeight/2) - (fHeight/2)*(m_lightgun.sThumbLY+0.5f)/32767.5f;


	if ( ( fThumbLX > m_nScreenX ) && ( fThumbLX < m_nScreenX + m_nScreenMaxX ) &&
		 ( fThumbLY > m_nScreenY ) && ( fThumbLY < m_nScreenY + m_nScreenMaxY ) )
	{
		m_zapperDat[0] = ((fThumbLX - m_nScreenX)*256)/m_nScreenMaxX ;
		m_zapperDat[1] = ((fThumbLY - m_nScreenY)*240)/m_nScreenMaxY ;
	}
	else
	{
		m_zapperDat[0] = 0 ;
		m_zapperDat[1] = 0 ;
	}

	/*
   *x=*x*VNSWID/(t.right?t.right:1);
   *y=*y*totallines/(t.bottom?t.bottom:1);
  }
  else
  {
   *x/=winsizemul;
   *y/=winsizemul;
  }
  *x+=VNSCLIP;
 }

 *y+=srendline;
*/
}

#endif

void CXBoxSample::handleEvents()
{

    INT32 resistance ;
	float newRes ;
	static int doInsert[4] = {0,0,0,0} ;
	static int doChange[4] = {0,0,0,0} ;

	if ( g_app->pollXBoxControllers() )
	{
		m_state = MAIN_MENU ;
		return ;
	}
	
	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] ;
			}
		}
	}

	m_joypad = ( g_app->m_emuControllers[0] & 0xFF ) | ( ( g_app->m_emuControllers[1] & 0xFF ) << 8 )  | 
				( ( g_app->m_emuControllers[2] & 0xFF ) << 16 ) | ( ( g_app->m_emuControllers[3] & 0xFF ) << 24 ) ;


#ifdef LIGHTGUN
	if ( m_zapperNum )
	{
		doZapper() ;
	}
#endif

	if ( FCEUGameInfo.type==GIT_FDS )
	{
		for ( int i = 0 ; i < 4 ; i++ )
		{
			if ( g_app->m_emuControllers[i] & INSERT_FDS )
			{
				if ( ! doInsert[i] )
				{
					FDSControl(FDS_IDISK);
					doInsert[i] = 1 ;
				}
			}
			else
			{
				doInsert[i] = 0 ;
			}

			if ( g_app->m_emuControllers[i] & CHANGE_FDS ) 
			{
				if ( ! doChange[i] )
				{
					FDSControl(FDS_SELECT);
					doChange[i] = 1 ;
				}
			}
			else
			{
				doChange[i] = 0 ;
			}
		}
	}
}



void CXBoxSample::xboxSaveState() 
{
	if ( m_bStateMenu )
	{
		int statenum ;
		g_app->m_state = IN_GAME_PAUSED ;
		g_app->m_sound.pause( TRUE ) ;

		#ifdef NEED_CDDA
		g_app->m_cdda.pause(TRUE) ;
		#endif

		statenum = selectState() ;

		freeTextures() ;
		m_sound.pause( FALSE ) ;

		#ifdef NEED_CDDA
		m_cdda.pause(FALSE) ;
		#endif

		m_state = IN_GAME ;

		if ( statenum >= 0 )
		{
			m_stateNumber = statenum ;
		}
		else
		{
			return ;
		}
	}
	if ( g_statefile && strlen( g_statefile ) )
	{
		g_statefile[ strlen(g_statefile)-1 ] = '0' + m_stateNumber ;

		if ( m_bScreenshotSavestate )
		{
			xboxScreenshot() ;

			g_statefile[ strlen(g_statefile)-2 ] = 'p' ;

			MoveFileEx( g_szLastScreenshot, g_statefile, MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING ) ;

			g_statefile[ strlen(g_statefile)-2 ] = 't' ;
		}
		SaveState(  ) ;

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

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

	if ( m_bStateMenu )
	{
		int statenum ;
		g_app->m_state = IN_GAME_PAUSED ;
		g_app->m_sound.pause( TRUE ) ;

		#ifdef NEED_CDDA
		g_app->m_cdda.pause(TRUE) ;
		#endif

		statenum = selectState() ;

		freeTextures() ;
		m_sound.pause( FALSE ) ;

		#ifdef NEED_CDDA
		m_cdda.pause(FALSE) ;
		#endif

		m_state = IN_GAME ;

		if ( statenum >= 0 )
		{
			m_stateNumber = statenum ;
		}
		else
		{
			return ;
		}
	}
	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 ;

		sprintfx( "before loadstate %u\r\n", m_stateNumber ) ;

		LoadState(  ) ;
		sprintfx( "after loadstate %u\r\n", m_stateNumber ) ;

		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*240 ) ;

	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;

	g_szLastScreenshot[0] = 0 ;

	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 )  ;
			Texture->UnlockRect(0) ;
			return ; 

/*			fprintf(stderr, "WritePNG:  libpng problem (longjmp) while writing row %ld\n",
			wpng_info.height-j);
			++error;
			break;*/
		}
	}
	Texture->UnlockRect(0) ;
		
		/*
	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 )  ;

	strcpy( g_szLastScreenshot, scr_filename ) ;

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

void CXBoxSample::xboxThrottle( int throttle ) 
{
	if ( throttle ) 
	{
		if ( m_throttle <= 0 )
			m_throttle = m_throttleSpeed ;
	}
	else
		m_throttle = 0 ;
	
	//m_throttle = throttle ;
	//SpeedThrottle() ;
}

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( )
{
	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_sound.pause( FALSE ) ;
}

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


	m_sound.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) ;
			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) ;

	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) ;
	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) ;
			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) ;
	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 ;
}


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 ;
	}

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



void CXBoxSample::doConfigureGame( char *settingsname, char *keysname )
{

	int menuChoice ;

	menuChoice = 0 ;

	loadSettings( settingsname ) ;
	loadKeys( keysname ) ;


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

	
		swprintf( m_menuText[0], L"Game Configuration" );
		swprintf( m_menuText[1], L"Video Mode : %S", ( m_refreshRate == 0 ? "Auto-Detect" : ( m_refreshRate == 60 ? "NTSC" : "PAL" ) ) );
		swprintf( m_menuText[2], L"Clip Sides? : %S", ( m_clipSides ? "Yes" : "No" ) ) ;
#ifdef LIGHTGUN 
		switch ( m_zapperNum )
		{
			case 0 :
			{
				swprintf( m_menuText[3], L"Zapper is not used"  );
				break ;
			}
			case 1 :
			{
				swprintf( m_menuText[3], L"Zapper is plugged into port 1"  );
				break ;
			}
			case 2 :
			{
				swprintf( m_menuText[3], L"Zapper is plugged into port 2"  );
				break ;
			}
			default : break ;
		}
#endif
		swprintf( m_menuText[4], L"Configure Controllers"  );
		swprintf( m_menuText[5], L"Graphics Filter"  );
		
		
		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 6, 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 :
				{
					switch ( m_refreshRate )
					{
						case 0 : m_refreshRate = 60 ; break ;
						case 50 : m_refreshRate = 0 ; break ;
						case 60:
						default : m_refreshRate = 50 ; break ;
					}
					break ; 
				}
				case 1 :
				{
					m_clipSides = !m_clipSides ;
					break ; 
				}
				case 2 : m_zapperNum = (m_zapperNum+1)%3 ; break ;
				case 3 : doConfigureControllers() ; break ;
				case 4 : doChangeSWFilter() ; break ; 
				default : break ;
			}
		}


	}

	saveSettings( settingsname ) ;
	saveKeys( keysname ) ;

}


#define CD_SECS 60
#define CD_FRAMES 75


void CXBoxSample::initConsole( UINT32 idx, int isFavorite, int forceConfig )
{
	char                filename[500] ;
	char				shortpath[100] ;
	unsigned char       *gimage ;
	int                 ntsccol ;
	FILE				*infile ;
	UINT32				fsize ;
	char *forcebuf ;
	char isOther = 0 ;


	m_throttle = 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 ) ;
		}
	}

	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 (filename, ".MP3")) || (strstr (filename, ".mp3")) )
	{
		if ( m_mp3player.loadFile( filename, 1, 0, 9999999 ) )
		{
			//writexbox( "nonomp3\r\n") ;
		}
		else
		{
			//m_mp3player.insertSilence( 22050 ) ;
			m_mp3player.pause( FALSE ) ;
			m_state = MAIN_MENU ;
			return  ;
		}
	}

	if ( (strstr (filename, ".M3U")) || (strstr (filename, ".m3u")) )
	{
		if ( m_mp3player.loadPlaylist( filename ) )
		{
			//writexbox( "nonomp3\r\n") ;
		}
		else
		{
			//m_mp3player.insertSilence( 22050 ) ;
			m_mp3player.pause( FALSE ) ;
			m_state = MAIN_MENU ;
			return  ;
		}
	}


	char *p ;


	xbox_compatible_name( filename, shortpath ) ;


	sprintfx("init\r\n") ;

	strcpy( g_saveprefix, g_savePath ) ;
	strcat( g_saveprefix, "\\" ) ;
	strcat( g_saveprefix, shortpath ) ;
	p = strrchr(g_saveprefix, '.');
	if (p) *p = 0;

	CreateDirectory( g_saveprefix, NULL ) ;

	strcat( g_saveprefix, "\\" ) ;
	strcat( g_saveprefix, shortpath ) ;
	p = strrchr(g_saveprefix, '.');
	if (p) *p = 0;

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

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

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

	strcpy(g_statefile, g_saveprefix);
	strcat(g_statefile, ".st0");

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

	sprintfx("init\r\n") ;

	if ( g_bIsBoot )
	{
		g_bIsBoot = 0 ;
		struct stat s ;

		if ( stat( g_keysfile, &s ) != 0 )
		{
			if ( stat( "d:\\boot.key", &s ) == 0 )
			{
				CopyFile( "d:\\boot.key", g_keysfile, TRUE ) ;
			}
			else
			{
				saveKeys( g_keysfile ) ;
			}
		}
		if ( stat( g_settingsfile, &s ) != 0 )
		{
			if ( stat( "d:\\boot.stg", &s ) == 0 )
			{
				CopyFile( "d:\\boot.stg", g_settingsfile, TRUE ) ;
			}
			else
			{
				loadSettings( g_settingsfile ) ;
			}
		}
	}

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

	if ( forceConfig || loadSettings( g_settingsfile ) )
	{
		changeMenu( &m_skin.gameSelectMenu, &m_skin.otherMenu ) ;
		doConfigureGame( g_settingsfile, g_keysfile ) ;
		isOther = 1 ;
	}



	if ( g_autoLaunchGame )
	{
		m_pnlSplashGame.Render() ;
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
	}
	else
	{
		if ( m_bNetplay )
		{
			if ( !isOther )
				changeMenu( &m_skin.gameSelectMenu, &m_skin.otherMenu ) ;
			if ( setupNetplay() )
				return ;
			doTransition( &m_pnlBackgroundOther, &m_pnlSplashGame, m_skin.fade, 1 ) ;
		}
		else
		{
			if ( isOther )
			{
				doTransition( &m_pnlBackgroundOther, &m_pnlSplashGame, m_skin.fade, 1 ) ;
			}
			else
			{
				doTransition( &m_pnlBackgroundSelect, &m_pnlSplashGame, m_skin.fade, 1 ) ;
			}
		}
	}

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


	if ( isOther == 0 )
	{
		loadKeys( g_keysfile ) ;
	}

	sprintfx("init\r\n") ;

	global_error_message[0] = 0 ;


	m_numFrames = 0 ;

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

	sprintfx("init\r\n") ;

	PaletteChanged = 0 ;


	m_sound.init() ;

	sprintfx("init\r\n") ;


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

	sprintfx("init\r\n") ;


	if(!(FCEUI_Initialize()))
	{
		strcpy(global_error_message, "*loadgame" ) ;
		return ;
	}

	sprintfx("init\r\n") ;

	m_consoleMemory = RAM ;

        //GetBaseDirectory(argv[0]);
		FCEUI_SetBaseDirectory(g_savePath);

	sprintfx("init\r\n") ;

//        LoadConfig();
//        DoArgs(argc-2,&argv[1]);
        FCEUI_DisableSpriteLimitation(1);
        FCEUI_SaveExtraDataUnderBase(1);
        FCEUI_SetSnapName(0);
        FCEUI_SetRenderedLines(8,239,0,239) ;
        FCEUI_SetSoundVolume(250);
		//FCEUI_SetSoundQuality( 1 ) ;

  InitSpeedThrottle();

	sprintfx("init\r\n") ;

		FCEUI_SetDirOverride(FCEUIOD_NV, g_savePath ) ;
		FCEUI_SetDirOverride(FCEUIOD_STATE, g_savePath ) ;
		FCEUI_SetDirOverride(FCEUIOD_CHEATS, g_savePath ) ;

		ntsccol = 1 ;

		DriverInterface(DES_NTSCCOL,&ntsccol);

	sprintfx("init\r\n") ;

         FCEUI_Sound(44100);
         //FCEUI_Sound(48000);

	sprintfx("init\r\n") ;

	if ( m_bUsingSamba )
	{
		char smbfilename[1024] ;
		char *smbp ;
		int sambafile ;
		FILE *outfile ;


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

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


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

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



		if ( sambafile <= 0 )
		{
			return ;
		}

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

		outfile = fopen(filename, "wb") ;

		if ( outfile == NULL )
		{
			m_smb.close( sambafile ) ;
			return ;
		}

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

		char *fbuf = (char*) malloc( filesize ) ;

		m_smb.read(sambafile,fbuf, filesize) ;
		fwrite( fbuf, sizeof(char), filesize, outfile ) ;

		fclose(outfile) ;
		m_smb.close( sambafile ) ;

		free(fbuf) ;

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

		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( ) ;
				return ;
			}


			fbuf = (char*) malloc( filesize ) ;

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

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

			m_relax.Close() ;

			fwrite( fbuf, 1, filesize, outfile ) ;
			fclose( outfile ) ;
			free(fbuf) ;
		}
		else
		{
			return ;
		}


	}
	else if ( ( strncmp( filename, "S:", 2 ) == 0 ) || ( strncmp( filename, "s:", 2 ) == 0 ) )
	{
		char isofilename[1024] ;
		FILE *outfile ;
		int filesize ;
		char *fbuf ;
		int isofd ;


		if ( ( isofd = m_iso9660.OpenFile( filename+2 ) ) >= 0 )
		{
			sprintfx( "opened iso %s\r\n", filename ) ;
			filesize = m_iso9660.GetFileSize( isofd ) ;


			sprintf( isofilename, "Z:\\%s", shortpath ) ;
			strcpy(filename, isofilename) ;

			outfile = fopen(filename, "wb") ;

			if ( outfile == NULL )
			{
				m_iso9660.CloseFile(isofd) ;
				return ;
			}


			fbuf = (char*) malloc( filesize ) ;

			if ( !fbuf )
			{
				m_iso9660.CloseFile(isofd) ;
				return ;
			}

			if ( ! m_iso9660.ReadFile( isofd, (byte*)fbuf, filesize ) )
			{
				free(fbuf) ;
				m_iso9660.CloseFile(isofd) ;
				return ;
			}

			m_iso9660.CloseFile(isofd) ;

			fwrite( fbuf, 1, filesize, outfile ) ;
			fclose( outfile ) ;
			free(fbuf) ;
		}
		else
		{
			return ;
		}
	}

	cht_load();

	if ( m_refreshRate == 50 )
		FCEUI_SetVidSystem( 1 ) ;
	else
		FCEUI_SetVidSystem( 0 ) ;

	if(!(FCEUI_LoadGame(filename)))
	{
		strcpy(global_error_message, "*loadgame" ) ;
		return ;
	}

	if ( m_refreshRate == 0 )
	{
		if ( PAL )
		{
			m_refreshRate = 50 ;
		}
		else
		{
			m_refreshRate = 60 ;
		}
	}

	xbox_set_refreshrate( m_refreshRate ) ;


	// Create our texture
	init_texture();

	sprintfx("init\r\n") ;

	//if ( ( m_refreshRate == 60 ) && ( m_d3dpp.FullScreen_RefreshRateInHz == 50 ) )
		//m_forceFaster = 1 ;
	//else
		//m_forceFaster = 0 ;

	sprintfx("init\r\n") ;

	if ( m_zapperNum == 1 )
	{
		FCEUI_SetInput(0, SI_ZAPPER,m_zapperDat,0);
		FCEUI_SetInput(1, SI_GAMEPAD,&m_joypad,0);
	}
	else if ( m_zapperNum == 2 )
	{
		FCEUI_SetInput(0, SI_GAMEPAD,&m_joypad,0);
		FCEUI_SetInput(1, SI_ZAPPER, m_zapperDat,0);
	}
	else
	{
		FCEUI_SetInput(0, SI_GAMEPAD,&m_joypad,0);
		FCEUI_SetInput(1, SI_GAMEPAD,&m_joypad,0);
	}

	FCEU_ResetPalette() ;

	sprintfx("init\r\n") ;

	m_state = IN_GAME ;



	applyHardwareFilter();



	sprintfx("init\r\n") ;

	m_fAppTime = 0.0f ;

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

	m_steps = 0 ;

	QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev);

	//put 3 frames of data in the audio buffer
	//processEmu(FALSE) ;
	sprintfx("init\r\n") ;
	//processEmu(FALSE) ;
	//processEmu(FALSE) ;

	sprintfx("init\r\n") ;
	PaletteChanged = 1 ;
	//Then start it up
	m_sound.pause( FALSE ) ;

}



void CXBoxSample::cleanupConsole( )
{
	sprintfx( "done2\r\n") ;
	cht_save() ;
	sprintfx( "done2\r\n") ;

	CloseGame() ;
	sprintfx( "done2\r\n") ;

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

	sprintfx( "done2\r\n") ;
	//see loader_unload() for other things to free
}


void CXBoxSample::applyGameGenie( unsigned char *ROM, unsigned int romsize )
{
	unsigned char *currpos ;



	for ( unsigned int i = 0 ; i < m_numCheats ; i++ )
	{

		if ( ! m_cheatCodes[i].enabled )
			continue ;

		if ( ( m_cheatCodes[i].type & 0xF0 ) != 0x90 )
			continue ;

		if ( m_cheatCodes[i].type == 0x99 )   //6char code
		{
			currpos = ROM + m_cheatCodes[i].adr ; 

			while ( romsize > ( currpos-ROM) )
			{
				*currpos = ( m_cheatCodes[i].val & 0xFF) ;
				currpos += 0x8000 ;
			}
		}
		else  //8char code
		{
			currpos = ROM + ( m_cheatCodes[i].adr & 0x1FFF ) ; 

			while ( romsize > ( currpos-ROM ) )
			{
				//sprintfx( "checking for %u at %04.4X\r\n", ((unsigned char)m_cheatCodes[i].code[16]), currpos-ROM ) ;
				if ( *currpos == ((unsigned char)m_cheatCodes[i].code[16]) )
				{
				//sprintfx( "writing %u to %04.4X\r\n", m_cheatCodes[i].val, currpos-ROM ) ;
					*currpos = ( m_cheatCodes[i].val & 0xFF) ;
				}
				currpos += 0x2000 ;
			}
		}

	}
}



#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 ;
}





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 )
{
}
void xbox_set_RAM_location() 
{
	m_memory_locations[0] = RAM ;


}

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_feed_stream(unsigned char* pSound,long lBytes) 
{
//	g_app->m_sound.process(pSound, lBytes ) ;
	g_app->m_mp3player.process() ;
	//g_app->m_cdda.process() ;
}



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) 
{
	//writexbox( "before readinput") ;

	//return 0 ;

	//MEMORYSTATUS stat;

    // Get the memory status.
    //GlobalMemoryStatus( &stat );

	//sprintfx("available memory = %u\r\n", stat.dwAvailPhys  ) ;


	return ReadJoypad( port ) ;

	//writexbox( "after readinput") ;
	//return 0 ;
}

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

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

void xbox_put_image(int w, int h)
{
	//writexbox( "before render") ;
	//g_sound->process() ;
	//g_mp3player->process() ;
	//g_app->m_cdda.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") ;
}

void FCEUD_WriteSoundData(int32 *Buffer, int Count)
{
	g_sound->process( Buffer, Count ) ;
}

void FCEUD_PrintError(char *s)
{
	//sprintfx( s ) ;
	strcpy( global_error_message, s ) ;
	g_app->m_msgDelay = 180 ;
}

void  FCEUD_PrintNotice( char *msg ) 
{
	g_app->m_msgDelay = 180 ;
	strcpy( global_error_message, msg ) ;

	//swprintf( g_app->m_strMessage, L"%S", msg ) ;
	
}

void FCEUD_Message(char *text)
{
	sprintfx( text ) ;
}


void FCEUD_Update(uint8 *XBuff, int32 *Buffer, int Count)
{
 if(Count )
  FCEUD_WriteSoundData(Buffer,Count);
 else
	 sprintfx( "count of 0!!!!!!!!!!!!\r\n") ;
// FCEUD_BlitScreen(XBuff);

 //FCEUD_UpdateInput();
}

void FCEUD_UpdateInput(void)
{
}
void FCEUD_SetPalette(uint8 index, uint8 r, uint8 g, uint8 b)
{
	g_app->SetPalette( index, r, g, b ) ;
}

void FCEUD_GetPalette(uint8 i, uint8 *r, uint8 *g, uint8 *b)
{
	g_app->GetPalette( i, r, g, b ) ;
}
void FCEUD_BlitScreen(uint8 *XBuff)
{
}

int xbox_get_throttle()
{
	return g_app->m_throttle ;
}

void xbox_apply_game_genie( byte *ROM, unsigned int romsize)
{
	sprintfx( "about to apply gg\r\n") ;
	g_app->applyGameGenie( ROM, romsize ) ;

	//http://www.monmouth.com/~colonel/videogames/nes/genie.html
	/*
Game Genie code = SLXPLOVS (SMB3: infinite lives)
The following info is derived from SMB3.PAT:
CPU address: $9123
Compare value: $DE
Patch value: $BD

ROM address to start comparing: $9123 & $1FFF + $10 = $1133.

The value at offset $1133 in the ROM doesn't match, so move on to the next bank at $1133+$2000.
Doesn't match here either, so move on to the next bank. Continue like so and you will eventually reach
$3D133, where the value is indeed our compare value, $DE. Change it to $BD, and Mario will have a
minimum of 4 lives next time you play the game.
*/
}

#ifdef __cplusplus
}
#endif
void CXBoxSample::processEmu( BOOL render )
{
	static int whichframe = 0 ;
	static int skipframe = 0 ;

	//sprintfx( "proc1\r\n") ;
		
			updateCheats2() ;
	//sprintfx( "proc1\r\n") ;

			handleEvents();
	//sprintfx( "proc1\r\n") ;
			m_mp3player.process() ;
	//sprintfx( "proc1\r\n") ;

			EmLoopOnce();  //makes callback to the audio
	//sprintfx( "proc1\r\n") ;

			if ( render )
			{
				/*
				if ( m_throttle )
				{
					if ( whichframe++ % 4 == 0 )
					{
						render_to_texture();
						m_numFrames++ ;
					}
				}
				else
				*/
				//if ( whichframe++ % 15 )

				if ( m_throttle > 0 )
					m_throttle-- ;

				if ( m_throttle == 0 )
				{
	//sprintfx( "proc2\r\n") ;
					render_to_texture();
	//sprintfx( "proc2\r\n") ;
					m_numFrames++ ;
				}
			}

			//if ( m_sound.m_bDanger )
				//sprintfx(" start trapped in while\r\n") ;

			while ( m_sound.m_bDanger && ( m_state != MAIN_MENU ))
			{
	//sprintfx( "proc3\r\n") ;
				//skipframe++ ;
				//sprintf( global_error_message, "dropped frames %u", skipframe) ;
				//m_msgDelay = 30 ;
				//sprintfx(" trapped in while\r\n") ;
				updateCheats2() ;
				handleEvents();
				m_mp3player.process() ;
				EmLoopOnce();  //makes callback to the audio
			}
			
			/*
			if ( m_sound.m_bDanger )
			{
				skipframe++ ;
				sprintf( global_error_message, "dropped frames %u", skipframe) ;
				m_msgDelay = 30 ;
			}
			*/
			//m_sound.process( m_fAppTime, m_numFrames ) ;
 			


}


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

