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


char *ASPECT_RATIO_NAMES[] = { "None", "Default (Best-H)", "Default (Best-V)", "TV" } ;
float ASPECT_RATIOS[] = { 1.0f, 224.0f/144.0f, 144.0f/224.0f,320.0/240.0 } ;
#define NUM_ASPECT_RATIOS 4
#define DEFAULT_PATTERN_X 224
#define DEFAULT_PATTERN_Y 144

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


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

extern unsigned long ws_cyclesByLine ;
extern byte ws_key_start;
extern byte ws_key_left;
extern byte ws_key_right;
extern byte ws_key_up;
extern byte ws_key_down;
extern byte ws_key_button_1;
extern byte ws_key_button_2;
extern byte ws_key_left_y;
extern byte ws_key_right_y;
extern byte ws_key_up_y;
extern byte ws_key_down_y;
extern int  app_rotated ;
extern unsigned char *internalRam;


extern int ws_key_esc ;
int m_swanMode, m_swanColor, m_swanCycles, m_swanFlip ;

int WINAPI WinMain_oswan( char *filename, LPDIRECTSOUND8		dsound ) ;
int ws_rotated(void);

#ifdef __cplusplus
extern "C" {
#endif


int TopLine_c, BottomLine_c ;



#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, ... );
//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[2050] ;

//int errno ;

#ifdef __cplusplus
}
#endif

//_CRTIMP int * __cdecl _errno(void);
//_CRTIMP int errno;

typedef struct tagBITMAPINFOHEADER{
      DWORD  biSize;
      DWORD  biWidth;
      DWORD  biHeight;
      WORD   biPlanes;
      WORD   biBitCount ;
      DWORD  biCompression;
      DWORD  biSizeImage;
      DWORD  biXPelsPerMeter;
      DWORD  biYPelsPerMeter;
      DWORD  biClrUsed;
      DWORD  biClrImportant;

   } BITMAPINFOHEADER;

typedef struct tagRGBQUAD {
  BYTE    rgbBlue; 
  BYTE    rgbGreen; 
  BYTE    rgbRed; 
  BYTE    rgbReserved; 
} RGBQUAD; 

typedef struct BMP
{
	BITMAPINFOHEADER						BitmapInfoHeader;
	RGBQUAD									Palette[256];
} BMP;


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

#define PLATFORM_NAME "WONDERSWAN"
#define PLATFORM_SAV L"WONDERSWANXSAV"
#define READING_ROMS_STRING L"Reading wswanroms directory...please wait."
#define PLATFORM_INI "wonderswanx.ini"
#define PLAYTHING_INI "plaything.cfg"
#define PLATFORM_MEMORY_POINTER internalRam
#define THEMEMUSIC "D:\\WONDERSWANX.MP3"
#define PLATFORM_FILE_DIR m_defaultRomDir
#define DEFAULT_PARENT_DIR "D:\\wswanroms\\*"
#define CD_BUF_SECTORS 1
#define CD_DATA_BUFFER_SIZE CD_BUF_SECTORS*2352
#define PROJECTILE_DEF 4 
#define DEFAULT_SKIN "default_wonderswanx"
#define DEFAULT_SKIN_DIR "D:\\EMUSKINS"
#define MAIN_MENU_STRING L"WonderSwanX Main Menu"
#define MLINE 
#define DEFAULT_SAVE_PATH "E:\\SAVES\\WONDERSWANX"
//#define GAME_GENIE 1
#define EMU_RECORDING_SIZE ( sizeof(DWORD)*4*60*60*10 )

#define GAMESHARK_GBA_TYPE 0x01
#define GAMESHARK_GBC_TYPE 0x02
#define CODEBREAKER_TYPE   0x03

int CODE_LENGTHS[] = { 12, 16, 8, 12 } ;


#define CONSOLE_MEMORY_SIZE 0x10000
unsigned char *m_memory_locations[] = { internalRam  } ;
unsigned int  m_memory_sizes[] = { 0x10000 } ;

#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 ;
	unsigned char keyboard ;
} 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, 0 },
		{ "DPad Down", XBOX_DPAD_DOWN, 0 },
		{ "DPad Left", XBOX_DPAD_LEFT, 0 },
		{ "DPad Right", XBOX_DPAD_RIGHT, 0 },
		{ "Start", XBOX_START, 0 },
		{ "Back", XBOX_BACK, 0 },
		{ "Left Thumb", XBOX_LEFT_THUMB, 0 },
		{ "Right Thumb", XBOX_RIGHT_THUMB, 0 },
		{ "A", XBOX_A, 0 },
		{ "B", XBOX_B, 0 },
		{ "X", XBOX_X, 0 },
		{ "Y", XBOX_Y, 0 },
		{ "Black", XBOX_BLACK, 0 },
		{ "White", XBOX_WHITE, 0 },
		{ "LTrigger", XBOX_LEFT_TRIGGER, 0 },
		{ "RTrigger", XBOX_RIGHT_TRIGGER, 0 },
		{ "LThumb Up", XBOX_LTHUMB_UP, 0 },
		{ "LThumb Down", XBOX_LTHUMB_DOWN, 0 },
		{ "LThumb Left", XBOX_LTHUMB_LEFT, 0 },
		{ "LThumb Right", XBOX_LTHUMB_RIGHT, 0 },
		{ "RThumb Up", XBOX_RTHUMB_UP, 0 },
		{ "RThumb Down", XBOX_RTHUMB_DOWN, 0 },
		{ "RThumb Left", XBOX_RTHUMB_LEFT, 0 },
		{ "RThumb Right", XBOX_RTHUMB_RIGHT, 0 },
		{ "Nothing", 0, 0 },
	} ;

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

#define INPUT_UP           0x01
#define INPUT_DOWN         0x02
#define INPUT_LEFT         0x04
#define INPUT_RIGHT        0x08
#define INPUT_BUTTON1      0x10
#define INPUT_BUTTON2      0x20
#define INPUT_START        0x40
#define INPUT_INC_CYCLES   0x80
#define INPUT_DEC_CYCLES   0x100
#define INPUT_UP_Y         0x200
#define INPUT_DOWN_Y       0x400
#define INPUT_LEFT_Y       0x800
#define INPUT_RIGHT_Y      0x1000
#define ROTATE_SCREEN      0x2000


	BUTTON_DEFINITION g_emuButtonDefinitions[] = {
		{ "Up", INPUT_UP, 0 },
		{ "Down", INPUT_DOWN, 0 },
		{ "Left", INPUT_LEFT, 0 },
		{ "Right", INPUT_RIGHT, 0 },
		{ "Button 1", INPUT_BUTTON1, 0 },
		{ "Button 2", INPUT_BUTTON2, 0 },
		{ "Start", INPUT_START, 0 },
		{ "Increase Cycles", INPUT_INC_CYCLES, 0 },
		{ "Decrease Cycles", INPUT_DEC_CYCLES, 0 },
		{ "Up-Y", INPUT_UP_Y, 0 },
		{ "Down-Y", INPUT_DOWN_Y, 0 },
		{ "Left-Y", INPUT_LEFT_Y, 0 },
		{ "Right-Y", INPUT_RIGHT_Y, 0 },
		{ "Rotate Screen", ROTATE_SCREEN, 0 },
		{ "Nothing", 0 },
	} ;

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

#define DEFAULT_BUTTON1  XBOX_DPAD_UP
#define DEFAULT_BUTTON2  XBOX_DPAD_DOWN
#define DEFAULT_BUTTON3  XBOX_DPAD_LEFT
#define DEFAULT_BUTTON4  XBOX_DPAD_RIGHT
#define DEFAULT_BUTTON5  XBOX_A
#define DEFAULT_BUTTON6  XBOX_X
#define DEFAULT_BUTTON7  XBOX_START
#define DEFAULT_BUTTON8  XBOX_WHITE
#define DEFAULT_BUTTON9  XBOX_BLACK
#define DEFAULT_BUTTON10 XBOX_LTHUMB_UP
#define DEFAULT_BUTTON11 XBOX_LTHUMB_DOWN
#define DEFAULT_BUTTON12 XBOX_LTHUMB_LEFT
#define DEFAULT_BUTTON13 XBOX_LTHUMB_RIGHT
#define DEFAULT_BUTTON14 XBOX_Y
#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 ;



//-----------------------------------------------------------------------------
// 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 int     handleEvents() ;
	virtual int     init_texture() ;
	virtual void    copyOldSaves() ;
	virtual BOOL    SetRefreshRate(INT iRefreshRate);
	virtual int		init_white_texture();
	virtual int		render_to_texture( int w, int h) ;
	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() ;
#endif
	virtual void    doPlaythingClear( );
	virtual void    saveSettings( char *filename );
	virtual int     loadSettings( char *filename );
	void            doChangeVideoMode( );
	virtual void    doAutofireConfig( int port );
	virtual void    doMainMenu() ;
	virtual void    doSelectTransition() ;
	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    updateEmuSpecificCheats() ;
	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    doDeleteCode( int selected );
	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 int     unzipFile( char *zipfile, char *newfilename, int *zipnumber );
	virtual void    createLocal( char *origfilename, char *newfilename, char* zipfilename, int *zipnumber );
	void			applyHardwareFilter( ) ;
	virtual int		selectFile( char *filename, char *dirname, int canchangedir, int selectdir, int refreshlist, int initlist  );
	virtual void	viewPlaylist( );
	virtual void	managePlaylists( );
	virtual void	editPlaylist( char *filename );
	virtual void    doSettings2( );
	void            viewTextFile( char *filename ) ;
	virtual void    doScreenSize( int istext ) ;
	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    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) ;
	void            loadMostRecentSaveState( );
	virtual void    doMenuTextSettings( MENU_PARAMS *menuparams) ;
	virtual void    doMenuSpriteSettings( MENU_PARAMS *menuparams) ;
	virtual void    doScreenshotSize( MENU_PARAMS *menu );
	virtual void    doSavePlaything() ;
	void            setPalette( unsigned int *palette) ;
	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    doUtilities( );
	virtual void    doHelp( );
	virtual int     selectState( );
	virtual void    doSettings( );
	virtual void    doCheatCodes( );
	virtual void    doGameUtilities( );
	virtual void    deleteSaveFiles( int which, int onlyFavorites ) ;
	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	UpdatePalette(void);
	
	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    doEditGameGenie( int selected ) ;
	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() ;
	void            renderScreenKeyboard( );
	virtual void    getKeyboardString( char *buf, int bufsize ) ;
	void            musicControlMenu( CPanel *panel );
	void            doDefaultDirs();
	virtual void    doLoadEmuSpecificIni( char *szbuf) ;
	virtual void    doSaveEmuSpecificIni( FILE *outfile ) ;
	virtual void    doSaveConfig() ;
	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 int     unzipSwan( char *zipfile, char *newfilename );
	virtual void    doTextOffset() ;
	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    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);

	

	D3DCOLOR m_color_palette[256];
	int   m_p1Difficulty, m_p2Difficulty, m_p1Down, m_p2Down ;
	int m_paddleSensitivity ;
	int m_country ;
	int m_refreshRate ;
	int					m_smsFPS ;
	int m_skipNext ;
	float m_fGamma ;
	BMP      Bmp ;
	int m_useFM ;


	DWORD m_startTime ;
	int m_changedGenie ;
	DWORD m_joypad ;
	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 ;
	CPanel m_pnlGameScreen2 ;

	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	Texture2;
	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::init_texture()
{
//	return 1  ;


	D3DCOLOR *palette ;

	sprintfx( "begin inittext\r\n") ;
	xbox_print_memory() ;

	// Release any previous texture
	if (Texture) 
	{ 
		return 1 ;
		Texture->BlockUntilNotBusy() ;
		Texture->Release();
		Texture = NULL;
	}
	
	theWidth = (224+10)*2 ;
	theHeight = (144+10)*2 ;

	Init_2xSaI(555);


	// Create the texture
	if (D3DXCreateTextureFromFileInMemoryEx(m_pd3dDevice, GAMESCREEN_FILE, sizeof(GAMESCREEN_FILE),
		 theWidth, theHeight, 1, 0, D3DFMT_LIN_X1R5G5B5, 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
	if (D3DXCreateTextureFromFileEx(m_pd3dDevice, "D:\\gamescreen.png",
		 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)
	{
		if ( FAILED(m_pnlGameScreen.Create(m_pd3dDevice, Texture, FALSE, theWidth, theHeight)) )
		{
			popupMsg( "no create panel", &m_pnlBackgroundOther ) ;
		}
	}
	else
	{
		popupMsg( "no load texture", &m_pnlBackgroundOther ) ;
	}

	xbox_print_memory() ;
*/	
/*
	D3DXCreateTexture(m_pd3dDevice, theWidth, theHeight, 0, 0, D3DFMT_LIN_R5G6B5, D3DPOOL_DEFAULT, &Texture);
		if ( FAILED(m_pnlGameScreen.Create(m_pd3dDevice, Texture, FALSE, theWidth, theHeight)) )
		{
			popupMsg( "no create panel", &m_pnlBackgroundOther ) ;
		}

*/
//	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[ desc.Size ];

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

	xbox_print_memory() ;

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

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

	return 0;
}




void CXBoxSample::UpdatePalette(void)
{
	/*
    unsigned char	r, g, b;
    int				index;

    if (bitmap.pal.update == 0) return;

    for (index = 0; index < 32; index++)
    {
        if(bitmap.pal.color[index])
        {
			
			//if (UseDirectDraw && RegistryInfo.EnableDirectDraw)
			//{
	            r = bitmap.pal.color[index][0];
				g = bitmap.pal.color[index][1];
				b = bitmap.pal.color[index][2];

				r = r >> 3 ;
				g = g >> 2 ;
				b = b >> 3 ;

				pixel[index] = (r<<11) | ( g <<5 ) | b ;

			//}
			//else
			//{
	            //r = bitmap.pal.color[index][0];
				//g = bitmap.pal.color[index][1];
				//b = bitmap.pal.color[index][2];
			//}

			//r = (unsigned char)(255.0f * pow((float)r / 255.0f, 1.0f / m_fGamma) + 0.5f);
			//g = (unsigned char)(255.0f * pow((float)g / 255.0f, 1.0f / m_fGamma) + 0.5f);
			//b = (unsigned char)(255.0f * pow((float)b / 255.0f, 1.0f / m_fGamma) + 0.5f);

			//pixel[index] = MAKE_PIXEL(r, g, b);

			Bmp.Palette[0x00 | index].rgbRed	  = r;
			Bmp.Palette[0x00 | index].rgbGreen	  = g;
			Bmp.Palette[0x00 | index].rgbBlue	  = b;
			Bmp.Palette[0x20 | index].rgbRed	  = r;
			Bmp.Palette[0x20 | index].rgbGreen	  = g;
			Bmp.Palette[0x20 | index].rgbBlue	  = b;
			Bmp.Palette[0x40 | index].rgbRed	  = r;
			Bmp.Palette[0x40 | index].rgbGreen	  = g;
			Bmp.Palette[0x40 | index].rgbBlue	  = b;
        }
    }

    bitmap.pal.update = 0;
    memset(bitmap.pal.dirty, 0, 32);
	*/
}








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


	initConsole(gameSelected, isFavorite, forceConfig) ;

	//while ( m_state == IN_GAME )
	//{
		//processEmu( TRUE ) ;
	//}

	saveKeys( g_keysfile ) ;
	cleanupConsole() ;

	char tmpfilename[1024] ;

	//sprintf( tmpfilename, "%s\\%s\\SPRITES\\*", m_szSkinDir, m_szSkin) ;
	//m_plaything.LoadSprites( tmpfilename ) ;

	//m_sound.cleanup() ;
	m_state = MAIN_MENU ;
	m_sockNetplay.m_debugClientSock.Close() ;



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

	if ( !m_bBgmInGame )
	{
		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_swanMode, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_swanColor, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_swanCycles, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ;
	fwrite( &m_swanFlip, sizeof(unsigned int), 1, setfile ) ;

	fclose( setfile ) ;

}


void CXBoxSample::setPalette( unsigned int *palette)
{

	//m_pd3dPalette->Lock( &color_palette, 0 ) ;

	memset( color_palette, 0, 256*sizeof(D3DCOLOR) ) ;



	for (int i = 0; i < 128; i++)
	{
		color_palette[i] = palette[i] ;
	}

	//m_pd3dPalette->Unlock() ;

	//m_pd3dDevice->SetPalette( 0, m_pd3dPalette ) ;
}

int CXBoxSample::loadSettings( char *filename )
{

	FILE *setfile ;

	m_changedSettings = 0 ;

	setfile = fopen( filename, "rb" ) ;

	m_swanMode = 0 ;
	m_swanColor = 0 ;
	m_swanCycles = 256 ;
	m_swanFlip = 0 ;

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

	fread( &m_swanMode, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_swanColor, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_swanCycles, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ;
	fread( &m_swanFlip, 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 ) ) ;

			memcpy( &(m_cheatCodes[m_numCheats]),&code, sizeof(CHEAT_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( "Z:\\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, "Z:\\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( );
		m_pnlGameScreen.SetAlpha( 0x80) ;
		m_pnlGameScreen.Render(0,0,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;
		m_pnlGameScreen.SetAlpha( 0xFF) ;

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

}





int CXBoxSample::addEmuSpecificOptions( int start )
{

	//swprintf( m_menuText[start], L"Add CodeBreaker Code (GBA)");
	//swprintf( m_menuText[start+1], L"Add Gameshark Code (GBA)");
	//swprintf( m_menuText[start+2], L"Add Gameshark Code (GB/GBC)");

	return start ;

}

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

}




void CXBoxSample::doDeleteCode( int selected )
{
	CHEAT_CODE *tempbuf ;

	tempbuf = (CHEAT_CODE*)malloc( sizeof(CHEAT_CODE) * ( m_numCheats - 1 ) ) ;

	memcpy( tempbuf, m_cheatCodes, sizeof(CHEAT_CODE) * selected ) ;

	if ( selected < m_numCheats-1 )
	{
		memcpy( &(tempbuf[selected]), &(m_cheatCodes[selected+1]), sizeof(CHEAT_CODE) * ( (m_numCheats - selected ) - 1) ) ;
	}

	free( m_cheatCodes ) ;

	m_cheatCodes = tempbuf ;
	m_numCheats-- ;
}


void CXBoxSample::updateEmuSpecificCheats( ) 
{
	/*
	int gbcount = 0 ;
	int gbacount = 0 ;

	cheatsDeleteAll( false )  ;
	gbCheatRemoveAll() ;

	for ( int i = 0 ; i < m_numCheats ; i++ )
	{
		switch ( m_cheatCodes[i].type )
		{
			case GAMESHARK_GBA_TYPE  :
			{
				cheatsAddGSACode( m_cheatCodes[i].code, "", false ) ;
				gbacount++ ;
				if ( m_cheatCodes[i].enabled )
				{
					cheatsDisable( gbacount-1 ) ;
					cheatsEnable( gbacount-1 ) ;
				}
				else
				{
					cheatsEnable( gbacount-1 ) ;
					cheatsDisable( gbacount-1 ) ;
				}
				break ;
			}
			case GAMESHARK_GBC_TYPE :
			{
				gbAddGsCheat( m_cheatCodes[i].code, "" ) ;
				gbcount++ ;
				if ( m_cheatCodes[i].enabled )
				{
					gbCheatDisable( gbcount-1 ) ;
					gbCheatEnable( gbcount-1 ) ;
				}
				else
				{
					gbCheatEnable( gbcount-1 ) ;
					gbCheatDisable( gbcount-1 ) ;
				}
				break ;
			}
			case CODEBREAKER_TYPE :
			{
				cheatsAddCBACode( m_cheatCodes[i].code, "" ) ;
				gbacount++ ;
				if ( m_cheatCodes[i].enabled )
				{
					cheatsDisable( gbacount-1 ) ;
					cheatsEnable( gbacount-1 ) ;
				}
				else
				{
					cheatsEnable( gbacount-1 ) ;
					cheatsDisable( gbacount-1 ) ;
				}
				break ;
			}
		}
	}
	*/
}

void CXBoxSample::performEmuSpecificOption( int start, int menuChoice ) 
{
	/*
	if ( menuChoice == start )
	{
		doAddCodebreakerCode() ;
	}
	else if ( menuChoice == start+1 )
	{
		doAddGamesharkCodeGBA() ;
	}
	else if ( menuChoice == start+2 )
	{
		doAddGamesharkCodeGBC() ;
	}
	*/
}

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

	switch ( codetype )
	{
		default :
		{
			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 ;
			}
			break ;
		}
	}


	return 1 ;
}









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

	InitializeWithScreen() ;
    return S_OK;
}


int CXBoxSample::render_to_texture( int w, int h)
{
    int vp_vstart ;
    int vp_vend   ;
    int vp_hstart ;
    int vp_hend   ;
	RECT src, dst;
	WORD *curr1 ; 
	byte *curr2 ;
	DWORD pitchDiff1 ; 
	DWORD pitchDiff2 ; 
	D3DCOLOR *palette ;
	char palstr[200] ;
	DWORD pixel ;
	byte r,g,b ;

	m_numFrames++ ;

	w = 224 ;
	h = 144 ;

/*	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  ;

	curr2 = g_pBlitBuff ;
	pitchDiff1 = (m_pitch - 640 )/2;
	pitchDiff2 = m_pitch - 320 ;


	for ( int y = 0 ; y < MaxLines ; y++ )
	{
		for ( int x = 0 ; x < 320 ; x++ )
		{
			*curr1++ = (color_palette[*curr2&0x7f] & 0xFFFF);
			curr2++ ;
			//*curr1++ = (palette[*curr2++] & 0xFFFF);
		}

		curr2 += pitchDiff2 ;
		curr1 += pitchDiff1 ;
	}
*/






	float mx, my ;

	if ( m_xboxSFilter )
	{
		SOFTWARE_FILTERS[m_xboxSFilter].blitfunc(g_pBlitBuff + w*2,w*2, g_pDeltaBuff+m_pitch, ((unsigned char*)d3dlr.pBits), m_pitch, 224, 144, 0 ) ;
		//XGSwizzleRect(g_pBlitBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);
		//memcpy( d3dlr.pBits, g_pBlitBuff, desc.Size ) ;
		Texture->UnlockRect(0);
		//m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0x00000000, 1.0f, 0L );
		//RenderGradientBackground( 0xFF000000, 0xFF000000 );
		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)w*SOFTWARE_FILTERS[m_xboxSFilter].multiplier) ;
		my = (float)m_nScreenMaxY / ((float)h*SOFTWARE_FILTERS[m_xboxSFilter].multiplier);

		//m_gameRectSource.top = vp_vstart*2;
		//m_gameRectSource.left = vp_hstart*2;
		//m_gameRectSource.bottom = vp_vstart*2 + ( vp_vend-vp_vstart)*2;
		//m_gameRectSource.right  = vp_hend*2 + ( vp_hend-vp_hstart)*2;

		m_gameRectSource.top = 0 ;
		m_gameRectSource.left = 0 ; 
		m_gameRectSource.bottom = (h)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ; 
		m_gameRectSource.right  = (w)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ; 

	}
	else
	{
		//memcptsystemDrawScreenNoFilter( (unsigned char*)d3dlr.pBits) ;
		//XGSwizzleRect(g_pBlitBuff, 0, NULL, d3dlr.pBits, desc.Width, desc.Height, NULL, 2);


		unsigned char *src = g_pBlitBuff;
		unsigned char *dst = (unsigned char*)d3dlr.pBits;

		for ( int y = 0 ; y < h ; y++ )
		{
			memcpy( dst, src, w*2 ) ;
			dst += m_pitch ;
			src += w*2 ;
		}


		//memcpy( d3dlr.pBits, g_pBlitBuff, desc.Size ) ;
		Texture->UnlockRect(0);
		//m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0x00000000, 1.0f, 0L );
		//RenderGradientBackground( 0xFF000000, 0xFF000000 );
		g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
		g_pd3dDevice->BeginScene();

		mx = (float)m_nScreenMaxX / ((float)w) ;
		my = (float)m_nScreenMaxY / ((float)h);

		m_gameRectSource.top = 0;
		m_gameRectSource.left = 0;
		m_gameRectSource.bottom = h;
		m_gameRectSource.right  = w;
	}



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


	if ( m_swanFlip )
	//if ( ws_rotated() )
	{
		//m_pnlGameScreenRenderOnCube(float x, float y, float w, float h, float x2, float y2, float w2, float h2, int face, float rx, float ry, float rz)
		m_pnlGameScreen.RenderOnCube2( m_gameRectSource.left, m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY,1,0,0,90,640*VIDEOMODES[m_xboxVidmode].multx, 480*VIDEOMODES[m_xboxVidmode].multy, 0xff) ;
		//m_pnlGameScreen.RotateWorld( 90, 0, 0 ) ;
	}
	else
	{
		m_pnlGameScreen.Render( m_gameRectSource.left, m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;
	}

	//m_pnlGameScreen.Render(m_nScreenX ,m_nScreenY,m_nScreenMaxX*mx,m_nScreenMaxY*my) ;

//	Sprite->Draw(Texture, &m_gameRectSource, &m_gameVecScale, NULL, 0, &m_gameVecTranslate, 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   ) ;
		}
	}
	*/
	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] )
	{
		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   ) ;
		}
	}
*/

#ifdef LIGHTGUN
	if ( m_zapperNum )
	{
		if ( m_lightgun.wButtons & XINPUT_LIGHTGUN_ONSCREEN  )
		{
			FLOAT fWidth = 640.0f ;
			FLOAT fHeight = 480.0f ;
			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 );
		}
	}
#endif
	// End the scene.
	g_pd3dDevice->EndScene();

	//if ( !m_throttle )
		//g_pd3dDevice->BlockUntilVerticalBlank() ;

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

	/*
	float FPS, desiredFPS ;

	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);
		}
		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;
	
	// 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;
	*/
}
int CXBoxSample::handleExtension( char *ext, char *zipfile, char *newfilename, int *zipnumber )
{
	return 0 ;
}

void CXBoxSample::InitializeEmuSpecific()
{

	m_paddleSensitivity = 25 ;

	m_swanMode = 0;
	m_swanCycles = 256 ;
	m_swanColor = 0 ;
	m_swanFlip = 0 ;

	g_pUnpaletteBuff = NULL ;


	//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 ;
	FLOAT fHeight = 480.0f ;
    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

//extern int emulating ;




#define EMU_RESET			0x3B		//; F1  (Reset)
#define EMU_SELECT			0x3C		//; F2  (Select)
#define EMU_BW				0x3D		//; F3  (B/W)
#define EMU_COLOR			0x3E		//; F4  (Color)
#define EMU_P1EASY			0x3F		//; F5  (P0 easy)
#define EMU_P1HARD			0x40		//; F6  (P0 hard)
#define EMU_P2EASY			0x41		//; F7  (P1 easy)
#define EMU_P2HARD			0x42		//  F8  (P1 hard)


#define P1LEFT 		0x4B		//; p1 left
#define P1RIGHT		0x4D		//; p1 right
#define P1UP 		0x48		//; p1 up
#define P1DOWN 		0x50		//; p1 down
#define P1FIRE 		0x1d		//; p1 fire
#define P1BG_B 		0x36        //; p1 booster bg
#define P1BG_T 		0x35		//; p1 trigger bg

#define P2LEFT 			0x1f		//; S (P2 left)
#define P2RIGHT			0x21		//; F (P2 right)
#define P2UP 			0x12		//; E (P2 up)
#define P2DOWN 			0x20		//; D (P2 down)
#define P2FIRE 			0x31		//; N (P2 fire)
#define P2BG_T 			0x30		//; B (P2 booster grip - trigger)
#define P2BG_B 			0x2F		//; V (P2 booster grip - booster)


#define Key0 			0x00b
#define Key1 			0x002
#define Key2 			0x003
#define Key3 			0x004
#define Key4 			0x005
#define Key5 			0x006
#define Key6 			0x007
#define Key7 			0x008
#define Key8 			0x009
#define Key9 			0x00a

#define KeyQ 			0x010
#define KeyW 			0x011
#define KeyA 			0x01E
#define KeyZ 			0x02C
#define KeyX 			0x02D
#define KeyC 			0x02E
#define KeyU 			0x016
#define KeyI 			0x017
#define KeyO 			0x018
#define KeyJ 			0x024
#define KeyK 			0x025
#define KeyL 			0x026
#define KeyM 			0x032
#define KeyComma 		0x033		
#define KeyDot 		0x034		

#define KeyG 			0x022
#define KeyH 			0x023
#define KeyP 			0x019
#define KeyR 			0x013
#define KeyT 			0x014
#define KeyY 			0x015
#define KeyColon 		0x027

#define KeyS 			0x01f
#define KeyF 			0x021
#define KeyE 			0x012
#define KeyD 			0x020
#define KeyN 			0x031
#define KeyB 			0x030
#define KeyV 			0x02F

#define P1Pad1 	Key7
#define P1Pad2 	Key8
#define P1Pad3 	Key9
#define P1Pad4 	KeyU
#define P1Pad5 	KeyI
#define P1Pad6 	KeyO
#define P1Pad7 	KeyJ
#define P1Pad8 	KeyK
#define P1Pad9 	KeyL
#define P1PadStar 	KeyM			
#define P1Pad0 	KeyComma
#define P1PadPound 	KeyDot			

#define P2Pad1 	Key1
#define P2Pad2 	Key2
#define P2Pad3 	Key3
#define P2Pad4 	KeyQ
#define P2Pad5 	KeyW
#define P2Pad6 	KeyE
#define P2Pad7 	KeyA
#define P2Pad8 	KeyS
#define P2Pad9 	KeyD
#define P2PadStar 	KeyZ			
#define P2Pad0 	KeyX
#define P2PadPound 	KeyC		

int CXBoxSample::handleEvents()
{

    INT32 resistance ;
	float newRes ;
	static int didInc = 0 ;
	static int didDec = 0 ;
	static int didRotate = 0 ;

	updateCheats2() ;

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


	ws_key_start = m_emuControllers[0] & INPUT_START ? 1 : 0 ;
	ws_key_left = m_emuControllers[0] & INPUT_LEFT ? 1 : 0 ;
	ws_key_right = m_emuControllers[0] & INPUT_RIGHT ? 1 : 0 ;
	ws_key_up = m_emuControllers[0] & INPUT_UP ? 1 : 0 ;
	ws_key_down = m_emuControllers[0] & INPUT_DOWN ? 1 : 0 ;
	ws_key_button_1 = m_emuControllers[0] & INPUT_BUTTON1 ? 1 : 0 ;
	ws_key_button_2 = m_emuControllers[0] & INPUT_BUTTON2 ? 1 : 0 ;
	ws_key_left_y = m_emuControllers[0] & INPUT_LEFT_Y ? 1 : 0 ;
	ws_key_right_y = m_emuControllers[0] & INPUT_RIGHT_Y ? 1 : 0 ;
	ws_key_up_y = m_emuControllers[0] & INPUT_UP_Y ? 1 : 0 ;
	ws_key_down_y = m_emuControllers[0] & INPUT_DOWN_Y ? 1 : 0 ;

	if ( m_emuControllers[0] & ROTATE_SCREEN )
	{
		if ( didRotate == 0 )
		{
			app_rotated = !app_rotated ;
			m_swanFlip = !m_swanFlip ;
			didRotate = 1 ;
			sprintf( global_error_message, "Screen Rotated" ) ;
			m_msgDelay = 120 ;
		}
	}
	else
		didRotate = 0 ;

	if ( m_emuControllers[0] & INPUT_INC_CYCLES )
	{
		if ( didInc == 0 )
		{
			ws_cyclesByLine += 5 ;
			didInc = 1 ;
			sprintf( global_error_message, "Cycles Per Line = %u", ws_cyclesByLine  ) ;
			m_msgDelay = 120 ;
		}
	}
	else
		didInc = 0 ;

	if ( m_emuControllers[0] & INPUT_DEC_CYCLES )
	{
		if ( didDec == 0 )
		{
			ws_cyclesByLine -= 5 ;
			if (ws_cyclesByLine < 10 )
				ws_cyclesByLine = 10 ;
			didDec = 1 ;
			sprintf( global_error_message, "Cycles Per Line = %u", ws_cyclesByLine  ) ;
			m_msgDelay = 120 ;
		}
	}
	else
		didDec = 0 ;


	return 0 ;

}


int	ws_saveState(char *statepath);
int	ws_loadState(char *statepath);

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

		ws_saveState( g_statefile ) ;

		sprintf( global_error_message, "State %u Saved", m_stateNumber+1 ) ;
		//sprintf( global_error_message, "Save States Not Implemented", 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 ) ;

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

		//sprintf( global_error_message, "Save States Not Implemented", m_stateNumber+1 ) ;
		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_app->g_pDeltaBuff, 0xFF, 144*2*g_app->m_pitch ) ;

	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 ( strrchr( scr_filename, '.' ) == NULL )
				continue ;

			*(strrchr( 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)<<3) & 0xFF ;
			img_data[0] = ((pixel>>10)<<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 xthrottle ) 
{
	if ( xthrottle )
	{
		if ( g_throttle <= 0 )
			g_throttle = m_throttleSpeed ;
	}
	else
		g_throttle = 0 ;
	//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 ws_pause( int pause);

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 ) ;
	ws_pause(1) ;
	g_app->m_dwStartPause = GetTickCount();
	g_app->doCheatMenu() ;

	ws_pause(0) ;
	//m_mp3player.pause( !m_bBgmInGame ) ;

	//m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//m_pd3dDevice->Reset( &m_d3dpp ) ;
	//g_app->m_sound.pause( FALSE ) ;
	m_startTime = GetTickCount() ;
	m_numFrames = 0 ;
}

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





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"System Mode : %S", m_swanMode == 0 ? "Autodetect" : ( m_swanMode ==1 ? "Force Color" : "Force Mono" ) ) ;
		swprintf( m_menuText[2], L"Color Scheme : %S", m_swanColor == 0 ? "Default" : ( m_swanColor ==1 ? "Amber" : "Green" ) ) ;
		swprintf( m_menuText[3], L"Cycles Per Line : %u", m_swanCycles );
		swprintf( m_menuText[4], L"Revert Controllers : %S", m_swanFlip ? "Yes" : "No" );
		swprintf( m_menuText[5], L"Configure Controllers"  );
		swprintf( m_menuText[6], L"Set Graphics Filter"  );

		
		menuChoice = renderMenuTextWrapper( 1, menuChoice, m_menuText, 7, 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 : m_swanMode = (m_swanMode+1)%3 ; break ; 
				case 1 : m_swanColor = (m_swanColor+1)%3 ; break ; 
				case 2 : m_swanCycles = getValuePopup( "Cycles Per Line", m_swanCycles, 10, 1024, &m_pnlBackgroundOther ) ; break ;
				case 3 : m_swanFlip = !m_swanFlip ; break ; 
				case 4 : doConfigureControllers() ; break ; 
				case 5 : 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 ;
	int isOther ;


	m_bAutoLoadSaveState = 0 ;

	m_refreshRate = m_d3dpp.FullScreen_RefreshRateInHz ;

	m_skipNext = 0 ;

	sprintfx( "begin initcons\r\n") ;

	xbox_print_memory() ;

	isOther = 0 ;

	m_throttle = 0 ;

	for ( int i = 0 ; i < 4 ; i++ )
	{
		m_emuControllers[i] = 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 ) ;

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

	xbox_print_memory() ;

	char *p ;

	sprintfx("init\r\n") ;

	xbox_compatible_name( filename, shortpath ) ;

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

	xbox_print_memory() ;

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

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

	xbox_print_memory() ;
	sprintfx("init\r\n") ;

	global_error_message[0] = 0 ;




	if ( g_autoLaunchGame )
	{
		m_pnlSplashGame.Render() ;
		m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
	}
	else
	{
		if ( m_bNetplay )
		{
			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 ) ;
			}
		}
	}

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

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



	if ( !isOther )
	{
		loadKeys( g_keysfile ) ;
	}


	xbox_print_memory() ;


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

	xbox_print_memory() ;
	// Create our texture
	init_texture();

	//popupMsg( "is this panel on?", &m_pnlBackgroundOther) ;
	//popupMsg( "is this panel on?", &m_pnlGameScreen2) ;

	//m_pnlGameScreen.m_pTexture = NULL ;
	//m_pnlGameScreen.Create( m_pd3dDevice, Texture, FALSE, theWidth, theHeight ) ;

	sprintfx("init\r\n") ;

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

	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, "Z:\\%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, "Z:\\%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, isofd ;
		char *fbuf ;

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


	m_state = IN_GAME ;



	sprintfx("init\r\n") ;

	m_fAppTime = 0.0f ;

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

	m_steps = 0 ;
	//m_sound.pause( FALSE ) ;

	sprintfx( "about to vba_main %s\r\n", filename ) ;


	m_startTime = GetTickCount() ;

	//m_plaything.FreeSprites() ;




	QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev);

	//processEmu(FALSE) ;
	//sprintfx( "about to vba_main %s\r\n", filename ) ;
	//processEmu(FALSE) ;
	//processEmu(FALSE) ;

	xbox_set_refreshrate(60) ;

	//Then start it up
	//m_sound.pause( FALSE ) ;

	char uprfilename[500] ;

	strcpy( uprfilename, filename ) ;
	strupr( uprfilename ) ;

	if ( strstr( uprfilename, ".ZIP" ) )
	{
		unzipSwan( uprfilename, filename ) ;
		strcpy( uprfilename, filename ) ;
		strupr( uprfilename ) ;
	}

	applyHardwareFilter() ;

	WinMain_oswan( filename, m_sound.dsound ) ;

	ws_pause(1) ;

	//z26main( filename ) ;
	//vba_main( 0, filename, 	m_GBAuseBios,

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

	//sprintfx("init\r\n") ;
	//Then start it up


}



void CXBoxSample::cleanupConsole( )
{


	cht_save() ;


	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 )
{
	m_memory_locations[0] = 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_feed_stream(unsigned char* pSound,long lBytes) 
{
	//sprintfx( "before feed\r\n") ;
	//g_app->m_sound.process(pSound, lBytes ) ;
	g_app->m_mp3player.process() ;
	//sprintfx( "after feed\r\n") ;
	//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 char * xbox_get_screen_buffer()
{
	return g_app->g_pBlitBuff ;

}


int xbox_read_input(int port) 
{
	//writexbox( "before readinput") ;
	//return g_app->ReadJoypad( port ) ;
	//writexbox( "after readinput") ;
	return 0 ;
}

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

void xbox_put_image( int x, int y, int w, int h)
{
	//writexbox( "before render") ;
	//g_sound->process() ;
	g_mp3player->process() ;
	//g_app->m_sound.process( g_app->m_throttle ) ;

	if ( g_app->m_throttle )
		g_app->m_throttle-- ;

	if ( g_app->m_throttle == 0 )
		g_app->render_to_texture(x,y) ;

	//writexbox( "after render") ;
}

void xbox_set_palette( unsigned int *palette )
{
	g_app->setPalette( palette) ;
}


void xbox_Sleep( int d )
{
	Sleep( d ) ;
}

unsigned int xbox_read_port( int which )
{
	return g_app->m_emuControllers[which] ;
}

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


void xbox_open_zip( char *hugozipfile )
{
	//writexbox( "before zip") ;
	//g_app->rom_load_zip( hugozipfile ) ;
	//writexbox( "after zip") ;
}
void xbox_set_RAM_location() 
{
	m_memory_locations[0] = NULL ;


}

int xbox_get_filter()
{
	return g_app->m_xboxSFilter ;
}

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 )
{
/*			
			updateCheats2() ;

		    sms_frame( m_skipNext );

			if ( render  )
			{
				render_to_texture(1,1);
				m_numFrames++ ;
			}

			m_skipNext = m_sound.process( (char*)snd.buffer, snd.bufsize )  ;
			m_mp3player.process() ;
			UpdatePalette() ;
			handleEvents();
			
			while ( m_skipNext && ( m_state != MAIN_MENU ) )
			{
				sprintfx( "trapped in hold loop\r\n") ;
				updateCheats2() ;

				sms_frame( m_skipNext );

				m_skipNext = m_sound.process( (char*)snd.buffer, snd.bufsize )  ;
				m_mp3player.process() ;
				UpdatePalette() ;
				handleEvents();
			}

*/
}


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

int CXBoxSample::unzipSwan( char *zipfile, char *newfilename )
{
	byte c, *data, *header;
	int len = 0, rlen;

	OUTPUT_DEBUG_STRING( "unzipping\n") ;

	//writexbox( "ttt\r\n" ) ;
    unzFile file = unzOpen(zipfile);

    if(file == NULL)
		return 0 ;

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

    char filename[132];
    int filesize = 0;
    int port = unzGoToFirstFile(file);
    unz_file_info info;

	//writexbox( "ttt\r\n" ) ;
    while(port == UNZ_OK)
    {
		char name[132];
		unzGetCurrentFileInfo(file, &info, name,128, NULL,0, NULL,0);

		if ((int) info.uncompressed_size > filesize)
		{
			strcpy(filename,name);
			filesize = info.uncompressed_size;
		}
		port = unzGoToNextFile(file);
    }

	//writexbox( "ttt\r\n" ) ;
    if( !(port == UNZ_END_OF_LIST_OF_FILE || port == UNZ_OK) || filesize == 0)
    {
		unzClose(file) ;
		return 0 ;
    }
	//writexbox( "ttt\r\n" ) ;

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

    unzLocateFile(file,filename,1);
    unzGetCurrentFileInfo(file, &info, filename,128, NULL,0, NULL,0);
    
	//writexbox( "ttt\r\n" ) ;
    if( unzOpenCurrentFile(file) != UNZ_OK )
    {
		unzClose(file);
		return 0 ;
    }

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

	data = (byte*)malloc( info.uncompressed_size ) ;

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

	int l = unzReadCurrentFile(file,data,info.uncompressed_size);
	if(unzCloseCurrentFile(file) == UNZ_CRCERROR)
	{
		free(data) ;
	    unzClose(file);
		return 0 ;
	}

	//writexbox( "ttt\r\n" ) ;
    unzClose(file);

	sprintfx( "loadeddata\n" ) ;

	char *fptr = strrchr( zipfile, '\\' ) ;
	char *eptr = strrchr( filename, '.' ) ;
	char *gptr = strrchr( zipfile, '.' ) ;

	if ( gptr )
		*gptr = 0 ;

	if ( fptr )
	{
		sprintf( newfilename, "Z:\\%s%s", fptr+1,eptr  ) ;
	}
	else
	{
		sprintf( newfilename, "Z:\\%s%s", zipfile,eptr  ) ;
	}

	sprintfx( "newfile %s\n", newfilename );

	FILE *outfile = fopen( newfilename, "wb") ;

	if ( outfile )
	{
		sprintfx( "opened file %s\n", newfilename );
		fwrite( data, 1, info.uncompressed_size, outfile ) ;
		fclose( outfile ) ;
	}

	free(data) ;


	return 1;
}
