--- dosbox-0.74/do_configure	1970-01-01 01:00:00.000000000 +0100
+++ working-0.74/do_configure	2012-01-14 21:21:54.195000189 +0100
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+HOST=arm-gph-linux-gnueabi
+TARGET=arm-gph-linux-gnueabi
+SYSROOT=/home/sepulep/GPH_SDK/sys-root/usr/
+
+export HOST
+export TARGET
+export SYSROOT
+
+#CXXFLAGS "-mthumb-interwork"
+./configure --prefix=$SYSROOT --host=$HOST --target=$TARGET --build=`uname -m` \
+ CPPFLAGS="-I$SYSROOT/include" \
+ CXXFLAGS="-O3 -fomit-frame-pointer -fmerge-all-constants -ffast-math -fomit-frame-pointer -funswitch-loops -mcpu=arm926ej-s -mthumb-interwork" \
+ LDFLAGS="-L$SYSROOT/lib" \
+ --with-sdl-prefix=$SYSROOT \
+ --enable-core-inline --disable-fpu --disable-sdltest --disable-alsa-midi --disable-alsatest 
--- dosbox-0.74/include/mouse.h	2010-05-10 19:43:54.000000000 +0200
+++ working-0.74/include/mouse.h	2012-01-14 21:14:12.321000092 +0100
@@ -30,7 +30,7 @@
 
 void Mouse_ChangePS2Callback(Bit16u pseg, Bit16u pofs);
 
-
+void Mouse_CursorMovedFixed(float xpct,float ypct,bool emulate); // GP2X
 void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate);
 void Mouse_CursorSet(float x,float y);
 void Mouse_ButtonPressed(Bit8u button);
--- dosbox-0.74/include/render.h	2010-05-10 19:43:54.000000000 +0200
+++ working-0.74/include/render.h	2012-01-14 21:14:12.319000092 +0100
@@ -23,7 +23,7 @@
 // 1: complex scalers off, scaler cache off, all simple scalers on
 // 2: complex scalers off, scaler cache on
 // 3: complex scalers on
-#define RENDER_USE_ADVANCED_SCALERS 3
+#define RENDER_USE_ADVANCED_SCALERS 0
 
 #include "../src/gui/render_scalers.h"
 
--- dosbox-0.74/src/gui/sdlmain.cpp	2010-05-10 19:43:54.000000000 +0200
+++ working-0.74/src/gui/sdlmain.cpp	2012-01-14 21:14:12.322000092 +0100
@@ -35,6 +35,7 @@
 
 #include "cross.h"
 #include "SDL.h"
+#include "SDL_ttf.h"    // Used for OSD (GP2X/CAANOO)
 
 #include "dosbox.h"
 #include "video.h"
@@ -69,7 +70,10 @@
 
 #ifndef WGL_NV_allocate_memory
 #define WGL_NV_allocate_memory 1
-typedef void * (APIENTRY * PFNWGLALLOCATEMEMORYNVPROC) (int size, float readfreq, float writefreq, float priority);
+typedef void *(APIENTRY * PFNWGLALLOCATEMEMORYNVPROC) (int size,
+						       float readfreq,
+						       float writefreq,
+						       float priority);
 typedef void (APIENTRY * PFNWGLFREEMEMORYNVPROC) (void *pointer);
 #endif
 
@@ -85,7 +89,9 @@
 #ifndef GL_NV_pixel_data_range
 #define GL_NV_pixel_data_range 1
 #define GL_WRITE_PIXEL_DATA_RANGE_NV      0x8878
-typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target,
+						    GLsizei length,
+						    GLvoid * pointer);
 typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
 #endif
 
@@ -96,7 +102,7 @@
 #endif //C_OPENGL
 
 #if !(ENVIRON_INCLUDED)
-extern char** environ;
+extern char **environ;
 #endif
 
 #ifdef WIN32
@@ -106,9 +112,10 @@
 #include <windows.h>
 #if (HAVE_DDRAW_H)
 #include <ddraw.h>
-struct private_hwdata {
-	LPDIRECTDRAWSURFACE3 dd_surface;
-	LPDIRECTDRAWSURFACE3 dd_writebuf;
+struct private_hwdata
+{
+  LPDIRECTDRAWSURFACE3 dd_surface;
+  LPDIRECTDRAWSURFACE3 dd_writebuf;
 };
 #endif
 
@@ -117,7 +124,7 @@
 #define DEFAULT_CONFIG_FILE "/dosbox.conf"
 #elif defined(MACOSX)
 #define DEFAULT_CONFIG_FILE "/Library/Preferences/DOSBox Preferences"
-#else /*linux freebsd*/
+#else /*linux freebsd */
 #define DEFAULT_CONFIG_FILE "/.dosboxrc"
 #endif
 
@@ -132,1031 +139,2351 @@
 #include <os2.h>
 #endif
 
-enum SCREEN_TYPES	{
-	SCREEN_SURFACE,
-	SCREEN_SURFACE_DDRAW,
-	SCREEN_OVERLAY,
-	SCREEN_OPENGL
+enum SCREEN_TYPES
+{
+  SCREEN_SURFACE,
+  SCREEN_SURFACE_DDRAW,
+  SCREEN_OVERLAY,
+  SCREEN_OPENGL
 };
 
-enum PRIORITY_LEVELS {
-	PRIORITY_LEVEL_PAUSE,
-	PRIORITY_LEVEL_LOWEST,
-	PRIORITY_LEVEL_LOWER,
-	PRIORITY_LEVEL_NORMAL,
-	PRIORITY_LEVEL_HIGHER,
-	PRIORITY_LEVEL_HIGHEST
+enum PRIORITY_LEVELS
+{
+  PRIORITY_LEVEL_PAUSE,
+  PRIORITY_LEVEL_LOWEST,
+  PRIORITY_LEVEL_LOWER,
+  PRIORITY_LEVEL_NORMAL,
+  PRIORITY_LEVEL_HIGHER,
+  PRIORITY_LEVEL_HIGHEST
 };
 
-
-struct SDL_Block {
-	bool inited;
-	bool active;							//If this isn't set don't draw
-	bool updating;
-	struct {
-		Bit32u width;
-		Bit32u height;
-		Bit32u bpp;
-		Bitu flags;
-		double scalex,scaley;
-		GFX_CallBack_t callback;
-	} draw;
-	bool wait_on_error;
-	struct {
-		struct {
-			Bit16u width, height;
-			bool fixed;
-		} full;
-		struct {
-			Bit16u width, height;
-		} window;
-		Bit8u bpp;
-		bool fullscreen;
-		bool doublebuf;
-		SCREEN_TYPES type;
-		SCREEN_TYPES want_type;
-	} desktop;
+struct SDL_Block
+{
+  bool inited;
+  bool active;			//If this isn't set don't draw
+  bool updating;
+  struct
+  {
+    Bit32u width;
+    Bit32u height;
+    Bit32u bpp;
+    Bitu flags;
+    double scalex, scaley;
+    GFX_CallBack_t callback;
+  } draw;
+  bool wait_on_error;
+  struct
+  {
+    struct
+    {
+      Bit16u width, height;
+      bool fixed;
+    } full;
+    struct
+    {
+      Bit16u width, height;
+    } window;
+    Bit8u bpp;
+    bool fullscreen;
+    bool doublebuf;
+    SCREEN_TYPES type;
+    SCREEN_TYPES want_type;
+  } desktop;
 #if C_OPENGL
-	struct {
-		Bitu pitch;
-		void * framebuf;
-		GLuint texture;
-		GLuint displaylist;
-		GLint max_texsize;
-		bool bilinear;
-		bool packed_pixel;
-		bool paletted_texture;
+  struct
+  {
+    Bitu pitch;
+    void *framebuf;
+    GLuint texture;
+    GLuint displaylist;
+    GLint max_texsize;
+    bool bilinear;
+    bool packed_pixel;
+    bool paletted_texture;
 #if defined(NVIDIA_PixelDataRange)
-		bool pixel_data_range;
+    bool pixel_data_range;
 #endif
-	} opengl;
+  } opengl;
 #endif
-	struct {
-		SDL_Surface * surface;
+  struct
+  {
+    SDL_Surface *surface;
+    
 #if (HAVE_DDRAW_H) && defined(WIN32)
-		RECT rect;
+    RECT rect;
 #endif
-	} blit;
-	struct {
-		PRIORITY_LEVELS focus;
-		PRIORITY_LEVELS nofocus;
-	} priority;
-	SDL_Rect clip;
-	SDL_Surface * surface;
-	SDL_Overlay * overlay;
-	SDL_cond *cond;
-	struct {
-		bool autolock;
-		bool autoenable;
-		bool requestlock;
-		bool locked;
-		Bitu sensitivity;
-	} mouse;
-	SDL_Rect updateRects[1024];
-	Bitu num_joysticks;
+  } blit;
+  struct
+  {
+    PRIORITY_LEVELS focus;
+    PRIORITY_LEVELS nofocus;
+  } priority;
+  SDL_Rect clip;
+  SDL_Surface *surface;
+  SDL_Overlay *overlay;
+  SDL_Surface *Debug_surface; //CAANOO
+  SDL_Surface *OSD_surface; //CAANOO
+  SDL_cond *cond;
+  struct
+  {
+    bool autolock;
+    bool autoenable;
+    bool requestlock;
+    bool locked;
+    Bitu sensitivity;
+  } mouse;
+  SDL_Rect updateRects[1024];
+  Bitu num_joysticks;
 #if defined (WIN32)
-	bool using_windib;
+  bool using_windib;
 #endif
-	// state of alt-keys for certain special handlings
-	Bit8u laltstate;
-	Bit8u raltstate;
+	TTF_Font *font;     // GP2X/CAANOO OSD Begin
+	int fontsize,fontwidth,fontheight;       // GP2X/CAANOO OSD Font Size
+	char title[200];
+	Uint32 fpstime;
+	int fps, curfps;    // GP2X/CAANOO OSD Enf
+
+  // state of alt-keys for certain special handlings
+  Bit8u laltstate;
+  Bit8u raltstate;
 };
 
 static SDL_Block sdl;
+extern const char* RunningProgram; // CAANOO (for debug)
+
+
+// borrowed from Zx-81 (http://zx81.zx81.free.fr )
+// CAANOO keys
+
+
+enum
+{
+     BTN_A = 0,     //       A /             1
+     BTN_X = 1,     //       X /             2
+     BTN_B = 2,     //       B /             3
+     BTN_Y = 3,     //       Y /             4
+     BTN_L = 4,     //       L /         5, L1
+     BTN_R = 5,     //       R /         6, L2
+     BTN_HOME = 6,  //    Home /         7, R1
+     BTN_HOLD = 7,  //    Hold /         8, R2
+     BTN_HELP1 = 8, //  Help I /        Select
+     BTN_HELP2 = 9, // Help II /         Start
+     BTN_TACT = 10, //    Tact / L Thumb Stick
+     BTN_UP = 11, 
+     BTN_DOWN = 12,
+     BTN_LEFT = 13,
+     BTN_RIGHT = 14,
+     // DIAGONALS
+     BTN_UP_LEFT = 15,
+     BTN_UP_RIGHT = 16,
+     BTN_DOWN_LEFT = 17,
+     BTN_DOWN_RIGHT = 18
+};
+
+void Caanoo_PushAnalogEvent(int btn, int pressed)
+{
+    SDL_Event event;
+# if 0 //ZX: DEBUG
+fprintf(stdout, "Caanoo_PushAnalogEvent %d %d %d\n", SDL_GetTicks(), btn, pressed);
+# endif
+    event.type = (pressed)?SDL_JOYBUTTONDOWN:SDL_JOYBUTTONUP;
+    event.jbutton.button = btn;
+    event.jbutton.state = (pressed)?SDL_PRESSED:SDL_RELEASED;
+    event.jbutton.which = 0;
+        
+    SDL_PushEvent(&event);      
+}
+
+SDL_Joystick* psp_sdl_joy;
+
+void Caanoo_UpdateAnalog(void)
+{
+    static int buttonsPrev = 0;
+    int buttonsNow = 0;
+        
+    SDL_JoystickUpdate();
+
+    int joy_x = SDL_JoystickGetAxis( psp_sdl_joy, 0 );
+    int joy_y = SDL_JoystickGetAxis( psp_sdl_joy, 1 );
+                
+    if (joy_x < -16384) buttonsNow = (1 << BTN_LEFT);
+    if (joy_x >  16384) buttonsNow = (1 << BTN_RIGHT);
+    if (joy_y < -16384) buttonsNow = (1 << BTN_UP);
+    if (joy_y >  16384) buttonsNow = (1 << BTN_DOWN);
+    
+    // DIAGONALS
+    if (joy_x > 11585 && joy_y < -11585)
+      buttonsNow = (1 << BTN_UP_RIGHT);
+    if (joy_x > 11585 && joy_y > 11585)
+      buttonsNow = (1 << BTN_DOWN_RIGHT);
+    if (joy_x < -11585 && joy_y > 11585)
+      buttonsNow = (1 << BTN_DOWN_LEFT);
+    if (joy_x < -11585 && joy_y < -11585)
+      buttonsNow = (1 << BTN_UP_LEFT);
+
+    if (buttonsNow != buttonsPrev)
+    {
+        if ((buttonsNow & (1 << BTN_LEFT)) != (buttonsPrev & (1 << BTN_LEFT)))
+        {
+                Caanoo_PushAnalogEvent(BTN_LEFT, (buttonsNow & (1 << BTN_LEFT)));
+        }
+        if ((buttonsNow & (1 << BTN_RIGHT)) != (buttonsPrev & (1 << BTN_RIGHT)))
+        {
+                Caanoo_PushAnalogEvent(BTN_RIGHT, (buttonsNow & (1 << BTN_RIGHT)));
+        }
+        if ((buttonsNow & (1 << BTN_UP)) != (buttonsPrev & (1 << BTN_UP)))
+        {
+                Caanoo_PushAnalogEvent(BTN_UP, (buttonsNow & (1 << BTN_UP)));
+        }
+        if ((buttonsNow & (1 << BTN_DOWN)) != (buttonsPrev & (1 << BTN_DOWN)))
+        {
+                Caanoo_PushAnalogEvent(BTN_DOWN, (buttonsNow & (1 << BTN_DOWN)));
+        }
+      // DIAGONALS
+      if ((buttonsNow & (1 << BTN_UP_RIGHT)) != (buttonsPrev & (1<< BTN_UP_RIGHT)))
+        {
+          Caanoo_PushAnalogEvent(BTN_UP_RIGHT, (buttonsNow & (1 << BTN_UP_RIGHT)));
+        }
+      if ((buttonsNow & (1 << BTN_DOWN_RIGHT)) != (buttonsPrev & (1<< BTN_DOWN_RIGHT)))
+        {
+          Caanoo_PushAnalogEvent(BTN_DOWN_RIGHT, (buttonsNow & (1 << BTN_DOWN_RIGHT)));
+        }
+      if ((buttonsNow & (1 << BTN_DOWN_LEFT)) != (buttonsPrev & (1<< BTN_DOWN_LEFT)))
+        {
+          Caanoo_PushAnalogEvent(BTN_DOWN_LEFT, (buttonsNow & (1 << BTN_DOWN_LEFT)));
+        }
+      if ((buttonsNow & (1 << BTN_UP_LEFT)) != (buttonsPrev & (1<< BTN_UP_LEFT)))
+        {
+          Caanoo_PushAnalogEvent(BTN_UP_LEFT, (buttonsNow & (1 << BTN_UP_LEFT)));
+        }
+    }
+    buttonsPrev = buttonsNow;
+}
+
+
+bool GP2X_ButtonPressed[19];
+
+void GP2X_LoadFont( int fontsize )
+{
+    if (sdl.font) TTF_CloseFont(sdl.font);
+
+    sdl.font=TTF_OpenFont("VeraMono.ttf", fontsize );
+    if (!sdl.font)  // Try again!
+        sdl.font=TTF_OpenFont("/mnt/sd/apps/dosbox/LiberationMono-Regular.ttf", fontsize );
+
+    if (!sdl.font)  // Didnt find the font
+    {
+        LOG_MSG("Could not load dbfont.ttf, GP2X debug disabled (%s)", TTF_GetError());
+    }
+    else
+    {
+        if (fontsize > 14 ) {
+            TTF_SetFontStyle(sdl.font, TTF_STYLE_BOLD );
+        }
+        else {
+            TTF_SetFontStyle(sdl.font, TTF_STYLE_NORMAL );
+        }
+    }
+}
+
+#define BASIC_COLORS      16
+#define VIRT_KEYBOARD      2
+#define VIRT_KEYBOARD_ROW  9
+#define VIRT_KEYBOARD_COL 10
+
+// Normal Keyboard Row
+#define VIRT_ROW_SHIFTBACK 5
+#define VIRT_ROW_LALTCTRL  6
+#define VIRT_ROW_RALTCTRL  7
+
+// Special Keyboard Row
+#define VIRT_ROW_INSHOM    0
+#define VIRT_ROW_DELEND    1
+#define VIRT_ROW_PGUPGD    2
+#define VIRT_ROW_ESCENTER  3
+#define VIRT_ROW_TABPAUSE  4
+#define VIRT_ROW_FUNCLABEL 5
+#define VIRT_ROW_FUNC1_10  6
+#define VIRT_ROW_FUNC1112  7
+// Both Keyboard Row
+#define VIRT_ROW_SPECIAL   8
+
+//    0   1   2   3   4   5   6   7   8   9
+char gp2x_keyboard[VIRT_KEYBOARD][VIRT_KEYBOARD_ROW][VIRT_KEYBOARD_COL] =
+{
+ { { '1','2','3','4','5','6','7','8','9','0' },
+   { 'a','b','c','d','e','f','g','h','i','j' },
+   { 'k','l','m','n','o','p','q','r','s','t' },
+   { 'u','v','w','x','y','z',' ',' ',' ',0x27 },
+   { '`','-','=','[',']',';',',','.','/','\\' },
+   { 'S','H','F','T',' ','B','A','C','K',' ' },
+   { 'L','A','L','T',' ','L','C','T','L',' ' },
+   { 'R','A','L','T',' ','R','C','T','L',' ' },
+   { 'S','P','E','C','I','A','L','K',0x27,'S' } },
+ { { 'I','N','S',' ',' ','H','O','M','E',' ' },
+   { 'D','E','L',' ',' ','E','N','D',' ',' ' },
+   { 'P','G','U','P',' ','P','G','D','W','N' },
+   { 'E','S','C',' ',' ','E','N','T','E','R' },
+   { 'T','A','B',' ',' ','P','A','U','S','E' },
+   { 'F','U','N','C',' ',' ','K','E','Y','S' },
+   { '1','2','3','4','5','6','7','8','9','0' },
+   { '1','1',' ',' ',' ','1','2',' ',' ',' ' },
+   { 'N','O','R','M','A','L','K','E','Y','S' } }
+};
+
+int gp2x_cur_kbd = 0;
+int gp2x_col_key = 0;
+int gp2x_row_key = 0;
+                                        //   r    g    b
+SDL_Color basic_colors[BASIC_COLORS] = { { 255, 255, 255, 0 },    //  0 = white
+                                         {   0,   0,   0, 0 },    //  1 = black
+                                         { 255,   0,   0, 0 },    //  2 = red
+                                         {   0,   0, 255, 0 },    //  3 = blue
+                                         {   0, 255,   0, 0 },    //  4 = green
+                                         { 255, 255,   0, 0 },    //  5 = yellow
+                                         {   0, 255, 255, 0 },    //  6 = cyan
+                                         { 255,   0, 127, 0 },    //  7 = pink
+                                         { 255, 127,   0, 0 },    //  8 = orange
+                                         {   0, 127, 127, 0 },    //  9 = dcyan
+                                         {  63,  63,  63, 0 },    // 10 = grey
+                                         { 191, 191, 191, 0 },    // 11 = ltgrey
+                                         {   0,   0, 127, 0 },    // 12 = dkblue
+                                         { 127,   0,   0, 0 },    // 13 = dkred
+                                         {   0, 127,   0, 0 },    // 14 = dkgreen
+                                         { 255,   0, 255, 0 } };  // 15 = use for transparent
+
+bool gp2x_shift          = false;
+bool gp2x_lalt           = false;
+bool gp2x_lctrl          = false;
+bool gp2x_ralt           = false;
+bool gp2x_rctrl          = false;
+bool gp2x_low_halfrow    = false;
+bool gp2x_up_halfrow     = false;
+bool gp2x_full_row       = false;
+
+#define OSD_STATE_NOBUFFER 1
+#define OSD_STATE_BUFFER   2
+int gp2x_osd_bufferstate = OSD_STATE_NOBUFFER; // Use defined states above
+bool gp2x_osd_debug     = false;
+bool gp2x_osd_virtkey   = false;
+bool gp2x_virtkey_press = false;
+bool debug_refresh      = false;
+bool osd_refresh      = false;
+
+// GP2X fullscreen/scale option
+bool gp2x_mouse          = true;
+bool button_state;
+int gp2x_mouse_speed     = 0;
+int gp2x_mouse_pixel     = 1;
+int GP2X_MOUSE_SPEED     = -1;
+
+bool gp2x_noclick        = false;
+bool blnStickUp          = false;
+bool blnStickDown        = false;
+bool blnStickLeft        = false;
+bool blnStickRight       = false;
+bool blnStickUpRight     = false;
+bool blnStickUpLeft      = false;
+bool blnStickDownRight   = false;
+bool blnStickDownLeft    = false;
+
+static void GP2X_EmuMouseToggle( bool pressed ) {
+	if (!pressed) return;
+    gp2x_mouse = !gp2x_mouse;
+}
+
+static void GP2X_NoClick( bool pressed ) {
+	if (!pressed) return;
+    gp2x_noclick = !gp2x_noclick;
+}
+
+static void GP2X_LeftClick( bool pressed ) {
+    if(pressed){
+        Mouse_ButtonPressed(0);
+    }
+    else {
+        Mouse_ButtonReleased(0);
+    }
+}
+
+static void GP2X_RightClick( bool pressed ) {
+    if(pressed){
+        Mouse_ButtonPressed(1);
+    }
+    else {
+        Mouse_ButtonReleased(1);
+    }
+}
+
+// begin GP2X OSD Color Variables
+int fontcolorset = 0;
+int fontcolor_front;
+int fontcolor_back;
+int fontcolor_frontsel;
+int fontcolor_backsel;
+
+// OSD GP2X block
+
+void GFX_CheckFontSize( void )
+{
+    int fontsize;
+    fontsize=14 * sdl.overlay->w/640;
+    if(fontsize<14) fontsize=14;
+    if( sdl.fontsize == fontsize ) return;
+    sdl.fontsize=fontsize;
+    GP2X_LoadFont( sdl.fontsize );
+    debug_refresh=true;
+    osd_refresh=true;
+
+    if(sdl.Debug_surface) SDL_FreeSurface(sdl.Debug_surface);
+    if(sdl.OSD_surface) SDL_FreeSurface(sdl.OSD_surface);
+    TTF_SizeText(sdl.font,"A",&sdl.fontwidth, &sdl.fontheight);
+    sdl.fontwidth--;
+
+    Uint32 rmask, gmask, bmask, amask;
+#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+    rmask = 0xff000000;
+    gmask = 0x00ff0000;
+    bmask = 0x0000ff00;
+    amask = 0x000000ff;
+#else
+    rmask = 0x000000ff;
+    gmask = 0x0000ff00;
+    bmask = 0x00ff0000;
+    amask = 0xff000000;
+#endif
+    sdl.Debug_surface=SDL_CreateRGBSurface(SDL_SWSURFACE,
+					sdl.overlay->w/2, sdl.fontheight,
+					32,rmask,gmask,bmask,0);
+    SDL_FillRect( sdl.Debug_surface, NULL, 
+      SDL_MapRGB(sdl.Debug_surface->format,basic_colors[fontcolor_back].r,basic_colors[fontcolor_back].g,basic_colors[fontcolor_back].b)  );   
+    sdl.OSD_surface=SDL_CreateRGBSurface(SDL_SWSURFACE,
+					sdl.fontwidth*VIRT_KEYBOARD_COL, sdl.fontheight*VIRT_KEYBOARD_ROW,
+					32,rmask,gmask,bmask,0);
+    SDL_FillRect( sdl.OSD_surface, NULL, 
+      SDL_MapRGB(sdl.OSD_surface->format,basic_colors[fontcolor_back].r,basic_colors[fontcolor_back].g,basic_colors[fontcolor_back].b)  );
+
+}
+
+/* from 32 bit RGB to UYVY overlay */
+void YUVBlit(SDL_Surface *s, SDL_Rect *src,SDL_Overlay *o, SDL_Rect *dest)
+{
+	int x,y;
+  SDL_Rect dsrc={0,0,s->w,s->h};
+  SDL_Rect ddest={0,0,o->w,o->h};
+	Uint8 *p,*op;
+  if(src == NULL) src=&dsrc; 
+  if(dest == NULL) dest=&ddest; 
+
+	SDL_LockSurface(s);
+//SDL_LockYUVOverlay(o);
+	for(y=src->y; y < (src->y+src->h) && y+dest->y < o->h; y++)
+	{
+		p=((Uint8 *) s->pixels)+s->pitch*y;
+		op=o->pixels[0]+o->pitches[0]*(y-src->y+dest->y)+dest->x*4;
+		for(x=src->x; x<(src->x+src->w) && x+dest->x<o->w; x++)
+		{
+    Bit8u red=*(p++);
+    Bit8u green=*(p++);
+    Bit8u blue=*(p++);
+    p++;
+    /* if(red ==255 && blue ==255) {op+=4; continue;} transparent not working atm*/
+    Bit8u y = (9797 * (red) + 19237 * (green) + 3734 * (blue)) >> 15;
+    Bit8u u = (18492 * ((blue) - (y)) >> 15) + 128;
+    Bit8u v = (23372 * ((red) - (y)) >> 15) + 128;
+    *(op++)=u;
+    *(op++)=y;
+    *(op++)=v;
+    *(op++)=y;
+		}
+	}
+
+//	SDL_UnlockYUVOverlay(o);
+	SDL_UnlockSurface(s);
+}
+
+
+// GP2X OSD Draw routine
+void GFX_OSD_Debug()
+{
+  if (sdl.fpstime == 0 || SDL_GetTicks()-sdl.fpstime>=1000) {
+      sdl.fps=sdl.curfps;
+      sdl.curfps=0;
+      sdl.fpstime=SDL_GetTicks();
+      debug_refresh=true;
+      }
+  sdl.curfps++;
+	if (sdl.Debug_surface)
+	{
+    if(debug_refresh)
+    {
+      char fpsdisp[300];
+      sprintf(fpsdisp, "%s FPS=%3d PGM=%s", sdl.title, sdl.fps, RunningProgram );
+      SDL_Color tcolorfg;
+      SDL_Color tcolorbg;
+      SDL_Surface *tsurf;
+  
+      tcolorfg = basic_colors[fontcolor_front];
+      tcolorbg = basic_colors[fontcolor_back];
+      tsurf = TTF_RenderText_Shaded(sdl.font, fpsdisp, tcolorfg, tcolorbg );
+      if (tsurf) {
+          SDL_Rect r;
+          r.x=0;r.y=0;
+          r.w=sdl.overlay->w;r.h=sdl.fontheight;
+          SDL_BlitSurface(tsurf,&r,sdl.Debug_surface,NULL);
+          SDL_FreeSurface(tsurf);
+      }
+    }
+    YUVBlit(sdl.Debug_surface,NULL,sdl.overlay,NULL);
+  }
+}
+
+void GFX_OSD_VirtKey()
+{
+  char key[2] = { 0x00, 0x00 };
+  int intCharWidth = 0, intCharHeight = 0;
+  SDL_Color tcolorfg;
+  SDL_Color tcolorbg;
+  SDL_Surface *tsurf;
+  SDL_Rect rectPosition;
+
+	if (sdl.OSD_surface)
+	{
+    if(osd_refresh)
+    {
+      intCharHeight = TTF_FontHeight( sdl.font );
+      rectPosition.x = 0;
+      rectPosition.y = sdl.OSD_surface->h - intCharHeight;
+  
+          // Draw the keyboard
+              for( int i=VIRT_KEYBOARD_ROW-1; i>=0; i-- )
+              {
+                  for( int j=0; j<VIRT_KEYBOARD_COL; j++ )
+                  {
+                      if( i == gp2x_row_key && ( j == gp2x_col_key ||
+                                                 j <  VIRT_KEYBOARD_COL/2 && gp2x_low_halfrow == true ||
+                                                 j >= VIRT_KEYBOARD_COL/2 && gp2x_up_halfrow  == true ||
+                                                 gp2x_full_row == true ) )
+                      {
+                          tcolorfg = basic_colors[fontcolor_frontsel];
+                          tcolorbg = basic_colors[fontcolor_backsel];
+                      }
+                      else
+                      {
+                          tcolorfg = basic_colors[fontcolor_front];
+                          tcolorbg = basic_colors[fontcolor_back];
+                      }
+  
+                      if( gp2x_shift == true && gp2x_cur_kbd == 0 )
+                      {
+                          if( gp2x_keyboard[gp2x_cur_kbd][i][j] >= 'a' &&
+                              gp2x_keyboard[gp2x_cur_kbd][i][j] <= 'z' )
+                          {
+                              key[0] = gp2x_keyboard[gp2x_cur_kbd][i][j] - 0x20;
+                          }
+                          else
+                          {
+                              switch( gp2x_keyboard[gp2x_cur_kbd][i][j] )
+                              {
+                                  case '1':  key[0] = '!'; break;
+                                  case '2':  key[0] = '@'; break;
+                                  case '3':  key[0] = '#'; break;
+                                  case '4':  key[0] = '$'; break;
+                                  case '5':  key[0] = '%'; break;
+                                  case '6':  key[0] = '^'; break;
+                                  case '7':  key[0] = '&'; break;
+                                  case '8':  key[0] = '*'; break;
+                                  case '9':  key[0] = '('; break;
+                                  case '0':  key[0] = ')'; break;
+                                  case '`':  key[0] = '~'; break;
+                                  case '-':  key[0] = '_'; break;
+                                  case '=':  key[0] = '+'; break;
+                                  case '[':  key[0] = '{'; break;
+                                  case ']':  key[0] = '}'; break;
+                                  case ',':  key[0] = '<'; break;
+                                  case '.':  key[0] = '>'; break;
+                                  case '/':  key[0] = '?'; break;
+                                  case ';':  key[0] = ':'; break;
+                                  case '\\': key[0] = '|'; break;
+                                  case 0x27: key[0] = '"'; break;
+                                  default :  key[0] = gp2x_keyboard[gp2x_cur_kbd][i][j]; break;
+                              }
+                          }
+                      }
+                      else
+                      {
+                          key[0] = gp2x_keyboard[gp2x_cur_kbd][i][j];
+                      }
+  
+                      tsurf = TTF_RenderText_Shaded(sdl.font, &key[0], tcolorfg, tcolorbg );
+                      if( tsurf )
+                      {
+                          SDL_BlitSurface(tsurf, NULL, sdl.OSD_surface, &rectPosition);
+                          rectPosition.x += sdl.fontwidth; /*tsurf->w;*/
+                          SDL_FreeSurface(tsurf);
+                      }
+                  }
+                  rectPosition.x = 0;
+                  rectPosition.y -= intCharHeight;
+              }
+	  osd_refresh=false;
+    }
+    SDL_Rect dest;
+    dest.x=0.;dest.y=sdl.overlay->h-sdl.OSD_surface->h;
+    YUVBlit(sdl.OSD_surface,NULL,sdl.overlay,&dest);
+  }  
+} // GP2X end
+
+
+void GP2X_OSD(void){
+  GFX_CheckFontSize();
+//  printf("%d\n",gp2x_osd_virtkey);
+  if(gp2x_osd_debug) GFX_OSD_Debug();
+  if(gp2x_osd_virtkey) GFX_OSD_VirtKey();
+}
+
+void GP2X_RefreshScreen( void )
+{
+    if( sdl.updating == false )
+    {
+        sdl.updating=true;
+        GFX_EndUpdate( NULL );
+    }
+}
+
+void GP2X_Debug_Toggle(bool pressed)
+{
+  debug_refresh=false;
+	if (!pressed) return;
+	gp2x_osd_debug=!gp2x_osd_debug;
+  debug_refresh=true;
+  GP2X_RefreshScreen();
+   (sdl.draw.callback) (GFX_CallBackRedraw);
+}
+
+void GP2X_VirtualKeyboard_Toggle( bool pressed )
+{
+//  printf("toggle \n");
+	if (!pressed) return;
+	gp2x_osd_virtkey=!gp2x_osd_virtkey;
+	osd_refresh=true;
+  (sdl.draw.callback) (GFX_CallBackRedraw);
+}
+
+int GP2X_VirtualKeyboard( SDL_Event* event )
+{
+    int intReturnKey = 0;
+    bool update_screen = false;
+    int GP2X_button = event->jbutton.button;
+    bool button_state = (event->type == SDL_JOYBUTTONDOWN) ? true : false;
+
+	  osd_refresh=true;
+
+
+    // Move to the new position
+    if( button_state )
+    {
+        switch( GP2X_button )
+        {
+            case BTN_DOWN:
+                gp2x_row_key++;
+                if( gp2x_row_key >= VIRT_KEYBOARD_ROW ) gp2x_row_key = 0;
+
+                if( gp2x_cur_kbd == 1 && gp2x_row_key == VIRT_ROW_FUNCLABEL ) gp2x_row_key++; // Dummy labels
+
+                if( gp2x_row_key == VIRT_ROW_SPECIAL )
+                {
+                    gp2x_low_halfrow    = false;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = true;
+                }
+                else
+                {
+                    gp2x_low_halfrow    = false;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = false;
+                }
+
+                if( (gp2x_cur_kbd == 0 && ( gp2x_row_key == VIRT_ROW_SHIFTBACK || gp2x_row_key == VIRT_ROW_LALTCTRL || gp2x_row_key == VIRT_ROW_RALTCTRL )) ||
+                    (gp2x_cur_kbd == 1 && ( gp2x_row_key == VIRT_ROW_INSHOM    || gp2x_row_key == VIRT_ROW_DELEND   ||
+                                            gp2x_row_key == VIRT_ROW_PGUPGD    || gp2x_row_key == VIRT_ROW_ESCENTER || gp2x_row_key == VIRT_ROW_TABPAUSE ||
+                                            gp2x_row_key == VIRT_ROW_FUNCLABEL || gp2x_row_key == VIRT_ROW_FUNC1112 )) )
+                {
+                    if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                    {
+                        gp2x_col_key = 0;
+                        gp2x_low_halfrow    = true;
+                        gp2x_up_halfrow     = false;
+                        gp2x_full_row       = false;
+                    }
+                    else
+                    {
+                        gp2x_col_key = VIRT_KEYBOARD_COL/2;
+                        gp2x_low_halfrow    = false;
+                        gp2x_up_halfrow     = true;
+                        gp2x_full_row       = false;
+                    }
+                }
+                update_screen = true;
+                break;
+            case BTN_UP:
+                gp2x_row_key--;
+                if( gp2x_row_key < 0 ) gp2x_row_key = VIRT_KEYBOARD_ROW-1;
+
+                if( gp2x_cur_kbd == 1 && gp2x_row_key == VIRT_ROW_FUNCLABEL ) gp2x_row_key--; // Dummy labels
+
+                if( gp2x_row_key == VIRT_ROW_SPECIAL )
+                {
+                    gp2x_low_halfrow    = false;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = true;
+                }
+                else
+                {
+                    gp2x_low_halfrow    = false;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = false;
+                }
+
+                if( (gp2x_cur_kbd == 0 && ( gp2x_row_key == VIRT_ROW_SHIFTBACK || gp2x_row_key == VIRT_ROW_LALTCTRL || gp2x_row_key == VIRT_ROW_RALTCTRL )) ||
+                    (gp2x_cur_kbd == 1 && ( gp2x_row_key == VIRT_ROW_INSHOM    || gp2x_row_key == VIRT_ROW_DELEND   ||
+                                            gp2x_row_key == VIRT_ROW_PGUPGD    || gp2x_row_key == VIRT_ROW_ESCENTER || gp2x_row_key == VIRT_ROW_TABPAUSE ||
+                                            gp2x_row_key == VIRT_ROW_FUNCLABEL || gp2x_row_key == VIRT_ROW_FUNC1112 )) )
+                {
+                    if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                    {
+                        gp2x_col_key = 0;
+                        gp2x_low_halfrow    = true;
+                        gp2x_up_halfrow     = false;
+                        gp2x_full_row       = false;
+                    }
+                    else
+                    {
+                        gp2x_col_key = VIRT_KEYBOARD_COL/2;
+                        gp2x_low_halfrow    = false;
+                        gp2x_up_halfrow     = true;
+                        gp2x_full_row       = false;
+                    }
+                }
+                update_screen = true;
+                break;
+            case BTN_RIGHT:
+                gp2x_col_key++;
+                if( gp2x_col_key >= VIRT_KEYBOARD_COL ) gp2x_col_key = 0;
+
+                if( (gp2x_cur_kbd == 0 && ( gp2x_row_key == VIRT_ROW_SHIFTBACK || gp2x_row_key == VIRT_ROW_LALTCTRL || gp2x_row_key == VIRT_ROW_RALTCTRL )) ||
+                    (gp2x_cur_kbd == 1 && ( gp2x_row_key == VIRT_ROW_INSHOM    || gp2x_row_key == VIRT_ROW_DELEND   ||
+                                            gp2x_row_key == VIRT_ROW_PGUPGD    || gp2x_row_key == VIRT_ROW_ESCENTER || gp2x_row_key == VIRT_ROW_TABPAUSE ||
+                                            gp2x_row_key == VIRT_ROW_FUNCLABEL || gp2x_row_key == VIRT_ROW_FUNC1112 )) )
+                {
+                    if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                    {
+                        gp2x_col_key = VIRT_KEYBOARD_COL/2;
+                        gp2x_low_halfrow    = false;
+                        gp2x_up_halfrow     = true;
+                        gp2x_full_row       = false;
+                    }
+                    else
+                    {
+                        gp2x_col_key = 0;
+                        gp2x_low_halfrow    = true;
+                        gp2x_up_halfrow     = false;
+                        gp2x_full_row       = false;
+                    }
+                }
+                update_screen = true;
+                break;
+            case BTN_LEFT:
+                gp2x_col_key--;
+                if( gp2x_col_key < 0 ) gp2x_col_key = VIRT_KEYBOARD_COL-1;
+
+                if( (gp2x_cur_kbd == 0 && ( gp2x_row_key == VIRT_ROW_SHIFTBACK || gp2x_row_key == VIRT_ROW_LALTCTRL || gp2x_row_key == VIRT_ROW_RALTCTRL )) ||
+                    (gp2x_cur_kbd == 1 && ( gp2x_row_key == VIRT_ROW_INSHOM    || gp2x_row_key == VIRT_ROW_DELEND   ||
+                                            gp2x_row_key == VIRT_ROW_PGUPGD    || gp2x_row_key == VIRT_ROW_ESCENTER || gp2x_row_key == VIRT_ROW_TABPAUSE ||
+                                            gp2x_row_key == VIRT_ROW_FUNCLABEL || gp2x_row_key == VIRT_ROW_FUNC1112 )) )
+                {
+                    if( gp2x_col_key < 0  )
+                    {
+                        gp2x_col_key = VIRT_KEYBOARD_COL/2;
+                        gp2x_low_halfrow    = false;
+                        gp2x_up_halfrow     = true;
+                        gp2x_full_row       = false;
+                    }
+                    else
+                    {
+                        gp2x_col_key = 0;
+                        gp2x_low_halfrow    = true;
+                        gp2x_up_halfrow     = false;
+                        gp2x_full_row       = false;
+                    }
+                }
+                update_screen = true;
+                break;
+        }
+    }
 
-extern const char* RunningProgram;
+    event->key.keysym.sym = (SDLKey)NULL;
+    switch( GP2X_button )
+    {
+        case BTN_HELP1:
+//            GP2X_VirtualKeyboard_Toggle( button_state );  
+            event->key.keysym.sym =(SDLKey)(SDLK_KP0 + BTN_HELP1);
+            //intReturnKey = 0; //?
+            break;
+        case BTN_L:
+        case BTN_R:
+            if( button_state )
+            {
+                gp2x_row_key = 0;
+                gp2x_col_key = 0;
+
+                if( gp2x_cur_kbd == 0)
+                {
+                    gp2x_cur_kbd = 1;
+                    gp2x_low_halfrow    = true;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = false;
+                }
+                else
+                {
+                    gp2x_cur_kbd = 0;
+                    gp2x_low_halfrow    = false;
+                    gp2x_up_halfrow     = false;
+                    gp2x_full_row       = false;
+                }
+                update_screen = true;
+            }
+            break;
+        case BTN_X:
+            event->key.keysym.sym = SDLK_BACKSPACE;
+            break;
+        case BTN_Y:
+            event->key.keysym.sym = SDLK_SPACE;
+            break;
+        case BTN_A:
+            event->key.keysym.sym = SDLK_RETURN;
+            break;
+        case BTN_B:
+            if( gp2x_cur_kbd == 0 )
+            {
+                switch( gp2x_row_key )
+                {
+                    case VIRT_ROW_SPECIAL:
+                        if( button_state )
+                        {
+                            gp2x_cur_kbd = 1;
+
+                            gp2x_row_key = 0;
+                            gp2x_col_key = 0;
+                            gp2x_low_halfrow    = true;
+                            gp2x_up_halfrow     = false;
+                            gp2x_full_row       = false;
+                            update_screen = true;
+                        }
+                        break;
+                    case VIRT_ROW_SHIFTBACK:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            if( button_state )
+                            {
+                                if( gp2x_shift == false )
+                                {
+                                    button_state = true;
+                                    gp2x_shift   = true;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_SHIFTBACK][(VIRT_KEYBOARD_COL/2)-1] = 'X';
+                                }
+                                else
+                                {
+                                    button_state = false;
+                                    gp2x_shift   = false;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_SHIFTBACK][(VIRT_KEYBOARD_COL/2)-1] = ' ';
+                                }
+                                update_screen = true;
+                                event->key.keysym.sym = SDLK_LSHIFT;
+                            }
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_BACKSPACE;
+                        }
+                        break;
+                    case VIRT_ROW_LALTCTRL:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            if( button_state )
+                            {
+                                if( gp2x_lalt == false )
+                                {
+                                    button_state = true;
+                                    gp2x_lalt    = true;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_LALTCTRL][(VIRT_KEYBOARD_COL/2)-1] = 'X';
+                                }
+                                else
+                                {
+                                    button_state = false;
+                                    gp2x_lalt    = false;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_LALTCTRL][(VIRT_KEYBOARD_COL/2)-1] = ' ';
+                                }
+                                update_screen = true;
+                                event->key.keysym.sym = SDLK_LALT;
+                            }
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            if( button_state )
+                            {
+                                if( gp2x_lctrl == false )
+                                {
+                                    button_state = true;
+                                    gp2x_lctrl   = true;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_LALTCTRL][VIRT_KEYBOARD_COL-1] = 'X';
+                                }
+                                else
+                                {
+                                    button_state = false;
+                                    gp2x_lctrl   = false;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_LALTCTRL][VIRT_KEYBOARD_COL-1] = ' ';
+                                }
+                                update_screen = true;
+                                event->key.keysym.sym = SDLK_LCTRL;
+                            }
+                        }
+                        break;
+                    case VIRT_ROW_RALTCTRL:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            if( button_state )
+                            {
+                                if( gp2x_ralt == false )
+                                {
+                                    button_state = true;
+                                    gp2x_ralt    = true;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_RALTCTRL][(VIRT_KEYBOARD_COL/2)-1] = 'X';
+                                }
+                                else
+                                {
+                                    button_state = false;
+                                    gp2x_ralt    = false;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_RALTCTRL][(VIRT_KEYBOARD_COL/2)-1] = ' ';
+                                }
+                                update_screen = true;
+                                event->key.keysym.sym = SDLK_RALT;
+                            }
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            if( button_state )
+                            {
+                                if( gp2x_rctrl == false )
+                                {
+                                    button_state = true;
+                                    gp2x_rctrl   = true;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_RALTCTRL][VIRT_KEYBOARD_COL-1] = 'X';
+                                }
+                                else
+                                {
+                                    button_state = false;
+                                    gp2x_rctrl   = false;
+                                    gp2x_keyboard[gp2x_cur_kbd][VIRT_ROW_RALTCTRL][VIRT_KEYBOARD_COL-1] = ' ';
+                                }
+                                update_screen = true;
+                                event->key.keysym.sym = SDLK_RCTRL;
+                            }
+                        }
+                        break;
+                    default:
+                        event->key.keysym.sym = (SDLKey)gp2x_keyboard[gp2x_cur_kbd][gp2x_row_key][gp2x_col_key];
+                        break;
+                }
+            }
+            else if( gp2x_cur_kbd == 1 )
+            {
+                switch( gp2x_row_key )
+                {
+                    case VIRT_ROW_SPECIAL:
+                        if( button_state )
+                        {
+                            gp2x_cur_kbd = 0;
+
+                            gp2x_row_key = 0;
+                            gp2x_col_key = 0;
+                            gp2x_low_halfrow    = false;
+                            gp2x_up_halfrow     = false;
+                            gp2x_full_row       = false;
+                            update_screen = true;
+                        }
+                        break;
+                    case VIRT_ROW_INSHOM:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_INSERT;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_HOME;
+                        }
+                        break;
+                    case VIRT_ROW_DELEND:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_DELETE;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_END;
+                        }
+                        break;
+                    case VIRT_ROW_PGUPGD:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_PAGEUP;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_PAGEDOWN;
+                        }
+                        break;
+                    case VIRT_ROW_ESCENTER:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_ESCAPE;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_RETURN;
+                        }
+                        break;
+                    case VIRT_ROW_TABPAUSE:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_TAB;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_PAUSE;
+                        }
+                        break;
+                    case VIRT_ROW_FUNC1_10:
+                        event->key.keysym.sym = (SDLKey)(SDLK_F1+gp2x_col_key);
+                        break;
+                    case VIRT_ROW_FUNC1112:
+                        if( gp2x_col_key < VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_F11;
+                        }
+                        else if( gp2x_col_key >= VIRT_KEYBOARD_COL/2 )
+                        {
+                            event->key.keysym.sym = SDLK_F12;
+                        }
+                        break;
+                    default:
+                        event->key.keysym.sym = (SDLKey)gp2x_keyboard[gp2x_cur_kbd][gp2x_row_key][gp2x_col_key];
+                        break;
+                }
+            }
+            break;
+    }
+
+    if( event->key.keysym.sym != (SDLKey)NULL )
+    {
+        if( button_state )
+        {
+            event->type      = SDL_KEYDOWN;
+            event->key.state = SDL_PRESSED;
+        }
+        else
+        {
+            event->type      = SDL_KEYUP;
+            event->key.state = SDL_RELEASED;
+        }
+        event->key.keysym.scancode   = 0;
+        event->key.keysym.mod        = KMOD_NONE;
+        event->key.keysym.unicode    = 0;
+        intReturnKey = 1;
+    }
+
+    if( update_screen == true )
+    {
+        GP2X_RefreshScreen();
+    }
+
+    return intReturnKey;
+}
+
+// \CAANOO
+
+extern const char *RunningProgram;
 extern bool CPU_CycleAutoAdjust;
 //Globals for keyboard initialisation
-bool startup_state_numlock=false;
-bool startup_state_capslock=false;
-void GFX_SetTitle(Bit32s cycles,Bits frameskip,bool paused){
-	char title[200]={0};
-	static Bit32s internal_cycles=0;
-	static Bits internal_frameskip=0;
-	if(cycles != -1) internal_cycles = cycles;
-	if(frameskip != -1) internal_frameskip = frameskip;
-	if(CPU_CycleAutoAdjust) {
-		sprintf(title,"DOSBox %s, Cpu speed: max %3d%% cycles, Frameskip %2d, Program: %8s",VERSION,internal_cycles,internal_frameskip,RunningProgram);
-	} else {
-		sprintf(title,"DOSBox %s, Cpu speed: %8d cycles, Frameskip %2d, Program: %8s",VERSION,internal_cycles,internal_frameskip,RunningProgram);
-	}
-
-	if(paused) strcat(title," PAUSED");
-	SDL_WM_SetCaption(title,VERSION);
-}
-
-static void PauseDOSBox(bool pressed) {
-	if (!pressed)
-		return;
-	GFX_SetTitle(-1,-1,true);
-	bool paused = true;
-	KEYBOARD_ClrBuffer();
-	SDL_Delay(500);
-	SDL_Event event;
-	while (SDL_PollEvent(&event)) {
-		// flush event queue.
-	}
-
-	while (paused) {
-		SDL_WaitEvent(&event);    // since we're not polling, cpu usage drops to 0.
-		switch (event.type) {
-
-			case SDL_QUIT: throw(0); break;
-			case SDL_KEYDOWN:   // Must use Pause/Break Key to resume.
-			case SDL_KEYUP:
-			if(event.key.keysym.sym==SDLK_PAUSE) {
-
-				paused=false;
-				GFX_SetTitle(-1,-1,false);
-				break;
-			}
-		}
+bool startup_state_numlock = false;
+bool startup_state_capslock = false;
+void
+GFX_SetTitle (Bit32s cycles, Bits frameskip, bool paused)
+{
+  char title[200] = { 0 };
+  static Bit32s internal_cycles = 0;
+  static Bits internal_frameskip = 0;
+  if (cycles != -1)
+    internal_cycles = cycles;
+  if (frameskip != -1)
+    internal_frameskip = frameskip;
+  if (CPU_CycleAutoAdjust)
+    {
+      sprintf (title,
+	       "DOSBox %s, Cpu speed: max %3d%% cycles, Frameskip %2d, Program: %8s",
+	       VERSION, internal_cycles, internal_frameskip, RunningProgram);
+    }
+  else
+    {
+      sprintf (title,
+	       "DOSBox %s, Cpu speed: %8d cycles, Frameskip %2d, Program: %8s",
+	       VERSION, internal_cycles, internal_frameskip, RunningProgram);
+    }
+
+  if (paused)
+    strcat (title, " PAUSED");
+  SDL_WM_SetCaption (title, VERSION);
+}
+
+static void
+PauseDOSBox (bool pressed)
+{
+  if (!pressed)
+    return;
+  GFX_SetTitle (-1, -1, true);
+  bool paused = true;
+  KEYBOARD_ClrBuffer ();
+  SDL_Delay (500);
+  SDL_Event event;
+  while (SDL_PollEvent (&event))
+    {
+      // flush event queue.
+    }
+
+  while (paused)
+    {
+      SDL_WaitEvent (&event);	// since we're not polling, cpu usage drops to 0.
+      switch (event.type)
+	{
+
+	case SDL_QUIT:
+	  throw (0);
+	  break;
+	case SDL_KEYDOWN:	// Must use Pause/Break Key to resume.
+	case SDL_KEYUP:
+	  if (event.key.keysym.sym == SDLK_PAUSE)
+	    {
+
+	      paused = false;
+	      GFX_SetTitle (-1, -1, false);
+	      break;
+	    }
 	}
+    }
 }
 
 #if defined (WIN32)
-bool GFX_SDLUsingWinDIB(void) {
-	return sdl.using_windib;
+bool
+GFX_SDLUsingWinDIB (void)
+{
+  return sdl.using_windib;
 }
 #endif
 
 /* Reset the screen with current values in the sdl structure */
-Bitu GFX_GetBestMode(Bitu flags) {
-	Bitu testbpp,gotbpp;
-	switch (sdl.desktop.want_type) {
-	case SCREEN_SURFACE:
-check_surface:
-		flags &= ~GFX_LOVE_8;		//Disable love for 8bpp modes
-		/* Check if we can satisfy the depth it loves */
-		if (flags & GFX_LOVE_8) testbpp=8;
-		else if (flags & GFX_LOVE_15) testbpp=15;
-		else if (flags & GFX_LOVE_16) testbpp=16;
-		else if (flags & GFX_LOVE_32) testbpp=32;
-		else testbpp=0;
+Bitu
+GFX_GetBestMode (Bitu flags)
+{
+  Bitu testbpp, gotbpp;
+  switch (sdl.desktop.want_type)
+    {
+    case SCREEN_SURFACE:
+    check_surface:
+      flags &= ~GFX_LOVE_8;	//Disable love for 8bpp modes
+      /* Check if we can satisfy the depth it loves */
+      if (flags & GFX_LOVE_8)
+	testbpp = 8;
+      else if (flags & GFX_LOVE_15)
+	testbpp = 15;
+      else if (flags & GFX_LOVE_16)
+	testbpp = 16;
+      else if (flags & GFX_LOVE_32)
+	testbpp = 32;
+      else
+	testbpp = 0;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-check_gotbpp:
+    check_gotbpp:
 #endif
-		if (sdl.desktop.fullscreen) gotbpp=SDL_VideoModeOK(640,480,testbpp,SDL_FULLSCREEN|SDL_HWSURFACE|SDL_HWPALETTE);
-		else gotbpp=sdl.desktop.bpp;
-		/* If we can't get our favorite mode check for another working one */
-		switch (gotbpp) {
-		case 8:
-			if (flags & GFX_CAN_8) flags&=~(GFX_CAN_15|GFX_CAN_16|GFX_CAN_32);
-			break;
-		case 15:
-			if (flags & GFX_CAN_15) flags&=~(GFX_CAN_8|GFX_CAN_16|GFX_CAN_32);
-			break;
-		case 16:
-			if (flags & GFX_CAN_16) flags&=~(GFX_CAN_8|GFX_CAN_15|GFX_CAN_32);
-			break;
-		case 24:
-		case 32:
-			if (flags & GFX_CAN_32) flags&=~(GFX_CAN_8|GFX_CAN_15|GFX_CAN_16);
-			break;
-		}
-		flags |= GFX_CAN_RANDOM;
-		break;
+      if (sdl.desktop.fullscreen)
+	gotbpp =
+	  SDL_VideoModeOK (640, 480, testbpp,
+			   SDL_FULLSCREEN | SDL_HWSURFACE | SDL_HWPALETTE);
+      else
+	gotbpp = sdl.desktop.bpp;
+      /* If we can't get our favorite mode check for another working one */
+      switch (gotbpp)
+	{
+	case 8:
+	  if (flags & GFX_CAN_8)
+	    flags &= ~(GFX_CAN_15 | GFX_CAN_16 | GFX_CAN_32);
+	  break;
+	case 15:
+	  if (flags & GFX_CAN_15)
+	    flags &= ~(GFX_CAN_8 | GFX_CAN_16 | GFX_CAN_32);
+	  break;
+	case 16:
+	  if (flags & GFX_CAN_16)
+	    flags &= ~(GFX_CAN_8 | GFX_CAN_15 | GFX_CAN_32);
+	  break;
+	case 24:
+	case 32:
+	  if (flags & GFX_CAN_32)
+	    flags &= ~(GFX_CAN_8 | GFX_CAN_15 | GFX_CAN_16);
+	  break;
+	}
+      flags |= GFX_CAN_RANDOM;
+      break;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	case SCREEN_SURFACE_DDRAW:
-		if (!(flags&(GFX_CAN_15|GFX_CAN_16|GFX_CAN_32))) goto check_surface;
-		if (flags & GFX_LOVE_15) testbpp=15;
-		else if (flags & GFX_LOVE_16) testbpp=16;
-		else if (flags & GFX_LOVE_32) testbpp=32;
-		else testbpp=0;
-		flags|=GFX_SCALING;
-		goto check_gotbpp;
-#endif
-	case SCREEN_OVERLAY:
-		if (flags & GFX_RGBONLY || !(flags&GFX_CAN_32)) goto check_surface;
-		flags|=GFX_SCALING;
-		flags&=~(GFX_CAN_8|GFX_CAN_15|GFX_CAN_16);
-		break;
+    case SCREEN_SURFACE_DDRAW:
+      if (!(flags & (GFX_CAN_15 | GFX_CAN_16 | GFX_CAN_32)))
+	goto check_surface;
+      if (flags & GFX_LOVE_15)
+	testbpp = 15;
+      else if (flags & GFX_LOVE_16)
+	testbpp = 16;
+      else if (flags & GFX_LOVE_32)
+	testbpp = 32;
+      else
+	testbpp = 0;
+      flags |= GFX_SCALING;
+      goto check_gotbpp;
+#endif
+    case SCREEN_OVERLAY:
+      if (flags & GFX_RGBONLY || !(flags & GFX_CAN_32))
+	goto check_surface;
+      flags |= GFX_SCALING;
+      flags &= ~(GFX_CAN_8 | GFX_CAN_15 | GFX_CAN_16);
+      break;
 #if C_OPENGL
-	case SCREEN_OPENGL:
-		if (flags & GFX_RGBONLY || !(flags&GFX_CAN_32)) goto check_surface;
-		flags|=GFX_SCALING;
-		flags&=~(GFX_CAN_8|GFX_CAN_15|GFX_CAN_16);
-		break;
-#endif
-	default:
-		goto check_surface;
-		break;
-	}
-	return flags;
+    case SCREEN_OPENGL:
+      if (flags & GFX_RGBONLY || !(flags & GFX_CAN_32))
+	goto check_surface;
+      flags |= GFX_SCALING;
+      flags &= ~(GFX_CAN_8 | GFX_CAN_15 | GFX_CAN_16);
+      break;
+#endif
+    default:
+      goto check_surface;
+      break;
+    }
+  return flags;
 }
 
 
-void GFX_ResetScreen(void) {
-	GFX_Stop();
-	if (sdl.draw.callback)
-		(sdl.draw.callback)( GFX_CallBackReset );
-	GFX_Start();
-	CPU_Reset_AutoAdjust();
-}
-
-static int int_log2 (int val) {
-    int log = 0;
-    while ((val >>= 1) != 0)
-	log++;
-    return log;
+void
+GFX_ResetScreen (void)
+{
+  GFX_Stop ();
+  if (sdl.draw.callback)
+    (sdl.draw.callback) (GFX_CallBackReset);
+  GFX_Start ();
+  CPU_Reset_AutoAdjust ();
+}
+
+static int
+int_log2 (int val)
+{
+  int log = 0;
+  while ((val >>= 1) != 0)
+    log++;
+  return log;
 }
 
 
-static SDL_Surface * GFX_SetupSurfaceScaled(Bit32u sdl_flags, Bit32u bpp) {
-	Bit16u fixedWidth;
-	Bit16u fixedHeight;
-
-	if (sdl.desktop.fullscreen) {
-		fixedWidth = sdl.desktop.full.fixed ? sdl.desktop.full.width : 0;
-		fixedHeight = sdl.desktop.full.fixed ? sdl.desktop.full.height : 0;
-		sdl_flags |= SDL_FULLSCREEN|SDL_HWSURFACE;
-	} else {
-		fixedWidth = sdl.desktop.window.width;
-		fixedHeight = sdl.desktop.window.height;
-		sdl_flags |= SDL_HWSURFACE;
-	}
-	if (fixedWidth && fixedHeight) {
-		double ratio_w=(double)fixedWidth/(sdl.draw.width*sdl.draw.scalex);
-		double ratio_h=(double)fixedHeight/(sdl.draw.height*sdl.draw.scaley);
-		if ( ratio_w < ratio_h) {
-			sdl.clip.w=fixedWidth;
-			sdl.clip.h=(Bit16u)(sdl.draw.height*sdl.draw.scaley*ratio_w);
-		} else {
-			sdl.clip.w=(Bit16u)(sdl.draw.width*sdl.draw.scalex*ratio_h);
-			sdl.clip.h=(Bit16u)fixedHeight;
-		}
-		if (sdl.desktop.fullscreen)
-			sdl.surface = SDL_SetVideoMode(fixedWidth,fixedHeight,bpp,sdl_flags);
-		else
-			sdl.surface = SDL_SetVideoMode(sdl.clip.w,sdl.clip.h,bpp,sdl_flags);
-		if (sdl.surface && sdl.surface->flags & SDL_FULLSCREEN) {
-			sdl.clip.x=(Sint16)((sdl.surface->w-sdl.clip.w)/2);
-			sdl.clip.y=(Sint16)((sdl.surface->h-sdl.clip.h)/2);
-		} else {
-			sdl.clip.x = 0;
-			sdl.clip.y = 0;
-		}
-		return sdl.surface;
-	} else {
-		sdl.clip.x=0;sdl.clip.y=0;
-		sdl.clip.w=(Bit16u)(sdl.draw.width*sdl.draw.scalex);
-		sdl.clip.h=(Bit16u)(sdl.draw.height*sdl.draw.scaley);
-		sdl.surface=SDL_SetVideoMode(sdl.clip.w,sdl.clip.h,bpp,sdl_flags);
-		return sdl.surface;
-	}
-}
+static SDL_Surface *
+GFX_SetupSurfaceScaled (Bit32u sdl_flags, Bit32u bpp)
+{
+  Bit16u fixedWidth;
+  Bit16u fixedHeight;
+  if (sdl.desktop.fullscreen)
+    {
+      fixedWidth = sdl.desktop.full.fixed ? sdl.desktop.full.width : 0;
+      fixedHeight = sdl.desktop.full.fixed ? sdl.desktop.full.height : 0;
+      sdl_flags |= SDL_FULLSCREEN;// | SDL_HWSURFACE; // GP2X
+    }
+  else
+    {
+      fixedWidth = sdl.desktop.window.width;
+      fixedHeight = sdl.desktop.window.height;
+//      sdl_flags |= SDL_HWSURFACE; //GP2X
+    }
+  if (fixedWidth && fixedHeight)
+    {
+      double ratio_w =
+	(double) fixedWidth / (sdl.draw.width * sdl.draw.scalex);
+      double ratio_h =
+	(double) fixedHeight / (sdl.draw.height * sdl.draw.scaley);
 
-Bitu GFX_SetSize(Bitu width,Bitu height,Bitu flags,double scalex,double scaley,GFX_CallBack_t callback) {
-	if (sdl.updating)
-		GFX_EndUpdate( 0 );
-
-	sdl.draw.width=width;
-	sdl.draw.height=height;
-	sdl.draw.callback=callback;
-	sdl.draw.scalex=scalex;
-	sdl.draw.scaley=scaley;
-
-	Bitu bpp=0;
-	Bitu retFlags = 0;
-
-	if (sdl.blit.surface) {
-		SDL_FreeSurface(sdl.blit.surface);
-		sdl.blit.surface=0;
-	}
-	switch (sdl.desktop.want_type) {
-	case SCREEN_SURFACE:
-dosurface:
-		if (flags & GFX_CAN_8) bpp=8;
-		if (flags & GFX_CAN_15) bpp=15;
-		if (flags & GFX_CAN_16) bpp=16;
-		if (flags & GFX_CAN_32) bpp=32;
-		sdl.desktop.type=SCREEN_SURFACE;
-		sdl.clip.w=width;
-		sdl.clip.h=height;
-		if (sdl.desktop.fullscreen) {
-			if (sdl.desktop.full.fixed) {
-				sdl.clip.x=(Sint16)((sdl.desktop.full.width-width)/2);
-				sdl.clip.y=(Sint16)((sdl.desktop.full.height-height)/2);
-				sdl.surface=SDL_SetVideoMode(sdl.desktop.full.width,sdl.desktop.full.height,bpp,
-					SDL_FULLSCREEN | ((flags & GFX_CAN_RANDOM) ? SDL_SWSURFACE : SDL_HWSURFACE) |
-					(sdl.desktop.doublebuf ? SDL_DOUBLEBUF|SDL_ASYNCBLIT : 0) | SDL_HWPALETTE);
-				if (sdl.surface == NULL) E_Exit("Could not set fullscreen video mode %ix%i-%i: %s",sdl.desktop.full.width,sdl.desktop.full.height,bpp,SDL_GetError());
-			} else {
-				sdl.clip.x=0;sdl.clip.y=0;
-				sdl.surface=SDL_SetVideoMode(width,height,bpp,
-					SDL_FULLSCREEN | ((flags & GFX_CAN_RANDOM) ? SDL_SWSURFACE : SDL_HWSURFACE) |
-					(sdl.desktop.doublebuf ? SDL_DOUBLEBUF|SDL_ASYNCBLIT  : 0)|SDL_HWPALETTE);
-				if (sdl.surface == NULL)
-					E_Exit("Could not set fullscreen video mode %ix%i-%i: %s",width,height,bpp,SDL_GetError());
-			}
-		} else {
-			sdl.clip.x=0;sdl.clip.y=0;
-			sdl.surface=SDL_SetVideoMode(width,height,bpp,(flags & GFX_CAN_RANDOM) ? SDL_SWSURFACE : SDL_HWSURFACE);
+      if (ratio_w < ratio_h)
+	{
+	  sdl.clip.w = fixedWidth;
+	  sdl.clip.h = (Bit16u) (sdl.draw.height * sdl.draw.scaley * ratio_w);
+	}
+      else
+	{
+	  sdl.clip.w = (Bit16u) (sdl.draw.width * sdl.draw.scalex * ratio_h);
+	  sdl.clip.h = (Bit16u) fixedHeight;
+	}
+  bpp=16; //GP2X 
+      if (sdl.desktop.fullscreen)
+	sdl.surface =
+	  SDL_SetVideoMode (fixedWidth, fixedHeight, bpp, sdl_flags);
+      else
+	sdl.surface =
+	  SDL_SetVideoMode (sdl.clip.w, sdl.clip.h, bpp, sdl_flags);
+      if (sdl.surface && sdl.surface->flags & SDL_FULLSCREEN)
+	{
+	  sdl.clip.x = (Sint16) ((sdl.surface->w - sdl.clip.w) / 2);
+	  sdl.clip.y = (Sint16) ((sdl.surface->h - sdl.clip.h) / 2);
+	}
+      else
+	{
+	  sdl.clip.x = 0;
+	  sdl.clip.y = 0;
+	}
+      return sdl.surface;
+    }
+  else
+    {
+      sdl.clip.x = 0;
+      sdl.clip.y = 0;
+      sdl.clip.w = (Bit16u) (sdl.draw.width * sdl.draw.scalex);
+      sdl.clip.h = (Bit16u) (sdl.draw.height * sdl.draw.scaley);
+      sdl.surface = SDL_SetVideoMode (sdl.clip.w, sdl.clip.h, bpp, sdl_flags);
+      return sdl.surface;
+    }
+}
+
+Bitu
+GFX_SetSize (Bitu width, Bitu height, Bitu flags, double scalex,
+	     double scaley, GFX_CallBack_t callback)
+{
+  if (sdl.updating)
+    GFX_EndUpdate (0);
+
+  sdl.draw.width = width;
+  sdl.draw.height = height;
+  sdl.draw.callback = callback;
+  sdl.draw.scalex = scalex;
+  sdl.draw.scaley = scaley;
+
+  Bitu bpp = 0;
+  Bitu retFlags = 0;
+
+  if (sdl.blit.surface)
+    {
+      SDL_FreeSurface (sdl.blit.surface);
+      sdl.blit.surface = 0;
+    }
+  switch (sdl.desktop.want_type)
+    {
+    case SCREEN_SURFACE:
+    dosurface:
+      if (flags & GFX_CAN_8)
+	bpp = 8;
+      if (flags & GFX_CAN_15)
+	bpp = 15;
+      if (flags & GFX_CAN_16)
+	bpp = 16;
+      if (flags & GFX_CAN_32)
+	bpp = 32;
+      sdl.desktop.type = SCREEN_SURFACE;
+      sdl.clip.w = width;
+      sdl.clip.h = height;
+      if (sdl.desktop.fullscreen)
+	{
+	  if (sdl.desktop.full.fixed)
+	    {
+	      sdl.clip.x = (Sint16) ((sdl.desktop.full.width - width) / 2);
+	      sdl.clip.y = (Sint16) ((sdl.desktop.full.height - height) / 2);
+	      sdl.surface =
+		SDL_SetVideoMode (sdl.desktop.full.width,
+				  sdl.desktop.full.height, bpp,
+				  SDL_FULLSCREEN | ((flags & GFX_CAN_RANDOM) ?
+						    SDL_SWSURFACE :
+						    SDL_HWSURFACE) | (sdl.
+								      desktop.
+								      doublebuf
+								      ?
+								      SDL_DOUBLEBUF
+								      |
+								      SDL_ASYNCBLIT
+								      : 0) |
+				  SDL_HWPALETTE);
+	      if (sdl.surface == NULL)
+		E_Exit ("Could not set fullscreen video mode %ix%i-%i: %s",
+			sdl.desktop.full.width, sdl.desktop.full.height, bpp,
+			SDL_GetError ());
+	    }
+	  else
+	    {
+	      sdl.clip.x = 0;
+	      sdl.clip.y = 0;
+	      sdl.surface = SDL_SetVideoMode (width, height, bpp,
+					      SDL_FULLSCREEN |
+					      ((flags & GFX_CAN_RANDOM) ?
+					       SDL_SWSURFACE : SDL_HWSURFACE)
+					      | (sdl.desktop.
+						 doublebuf ? SDL_DOUBLEBUF |
+						 SDL_ASYNCBLIT : 0) |
+					      SDL_HWPALETTE);
+	      if (sdl.surface == NULL)
+		E_Exit ("Could not set fullscreen video mode %ix%i-%i: %s",
+			width, height, bpp, SDL_GetError ());
+	    }
+	}
+      else
+	{
+	  sdl.clip.x = 0;
+	  sdl.clip.y = 0;
+	  sdl.surface =
+	    SDL_SetVideoMode (width, height, bpp,
+			      (flags & GFX_CAN_RANDOM) ? SDL_SWSURFACE :
+			      SDL_HWSURFACE);
 #ifdef WIN32
-			if (sdl.surface == NULL) {
-				SDL_QuitSubSystem(SDL_INIT_VIDEO);
-				if (!sdl.using_windib) {
-					LOG_MSG("Failed to create hardware surface.\nRestarting video subsystem with windib enabled.");
-					putenv("SDL_VIDEODRIVER=windib");
-					sdl.using_windib=true;
-				} else {
-					LOG_MSG("Failed to create hardware surface.\nRestarting video subsystem with directx enabled.");
-					putenv("SDL_VIDEODRIVER=directx");
-					sdl.using_windib=false;
-				}
-				SDL_InitSubSystem(SDL_INIT_VIDEO);
-				sdl.surface = SDL_SetVideoMode(width,height,bpp,SDL_HWSURFACE);
-			}
-#endif
-			if (sdl.surface == NULL)
-				E_Exit("Could not set windowed video mode %ix%i-%i: %s",width,height,bpp,SDL_GetError());
-		}
-		if (sdl.surface) {
-			switch (sdl.surface->format->BitsPerPixel) {
-			case 8:
-				retFlags = GFX_CAN_8;
-                break;
-			case 15:
-				retFlags = GFX_CAN_15;
-				break;
-			case 16:
-				retFlags = GFX_CAN_16;
-                break;
-			case 32:
-				retFlags = GFX_CAN_32;
-                break;
-			}
-			if (retFlags && (sdl.surface->flags & SDL_HWSURFACE))
-				retFlags |= GFX_HARDWARE;
-			if (retFlags && (sdl.surface->flags & SDL_DOUBLEBUF)) {
-				sdl.blit.surface=SDL_CreateRGBSurface(SDL_HWSURFACE,
-					sdl.draw.width, sdl.draw.height,
-					sdl.surface->format->BitsPerPixel,
-					sdl.surface->format->Rmask,
-					sdl.surface->format->Gmask,
-					sdl.surface->format->Bmask,
-				0);
-				/* If this one fails be ready for some flickering... */
-			}
+	  if (sdl.surface == NULL)
+	    {
+	      SDL_QuitSubSystem (SDL_INIT_VIDEO);
+	      if (!sdl.using_windib)
+		{
+		  LOG_MSG
+		    ("Failed to create hardware surface.\nRestarting video subsystem with windib enabled.");
+		  putenv ("SDL_VIDEODRIVER=windib");
+		  sdl.using_windib = true;
 		}
-		break;
+	      else
+		{
+		  LOG_MSG
+		    ("Failed to create hardware surface.\nRestarting video subsystem with directx enabled.");
+		  putenv ("SDL_VIDEODRIVER=directx");
+		  sdl.using_windib = false;
+		}
+	      SDL_InitSubSystem (SDL_INIT_VIDEO);
+	      sdl.surface =
+		SDL_SetVideoMode (width, height, bpp, SDL_HWSURFACE);
+	    }
+#endif
+	  if (sdl.surface == NULL)
+	    E_Exit ("Could not set windowed video mode %ix%i-%i: %s", width,
+		    height, bpp, SDL_GetError ());
+	}
+      if (sdl.surface)
+	{
+	  switch (sdl.surface->format->BitsPerPixel)
+	    {
+	    case 8:
+	      retFlags = GFX_CAN_8;
+	      break;
+	    case 15:
+	      retFlags = GFX_CAN_15;
+	      break;
+	    case 16:
+	      retFlags = GFX_CAN_16;
+	      break;
+	    case 32:
+	      retFlags = GFX_CAN_32;
+	      break;
+	    }
+	  if (retFlags && (sdl.surface->flags & SDL_HWSURFACE))
+	    retFlags |= GFX_HARDWARE;
+	  if (retFlags && (sdl.surface->flags & SDL_DOUBLEBUF))
+	    {
+	      sdl.blit.surface = SDL_CreateRGBSurface (SDL_HWSURFACE,
+						       sdl.draw.width,
+						       sdl.draw.height,
+						       sdl.surface->format->
+						       BitsPerPixel,
+						       sdl.surface->format->
+						       Rmask,
+						       sdl.surface->format->
+						       Gmask,
+						       sdl.surface->format->
+						       Bmask, 0);
+	      /* If this one fails be ready for some flickering... */
+	    }
+	}
+      break;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	case SCREEN_SURFACE_DDRAW:
-		if (flags & GFX_CAN_15) bpp=15;
-		if (flags & GFX_CAN_16) bpp=16;
-		if (flags & GFX_CAN_32) bpp=32;
-		if (!GFX_SetupSurfaceScaled((sdl.desktop.doublebuf && sdl.desktop.fullscreen) ? SDL_DOUBLEBUF : 0,bpp)) goto dosurface;
-		sdl.blit.rect.top=sdl.clip.y;
-		sdl.blit.rect.left=sdl.clip.x;
-		sdl.blit.rect.right=sdl.clip.x+sdl.clip.w;
-		sdl.blit.rect.bottom=sdl.clip.y+sdl.clip.h;
-		sdl.blit.surface=SDL_CreateRGBSurface(SDL_HWSURFACE,sdl.draw.width,sdl.draw.height,
-				sdl.surface->format->BitsPerPixel,
-				sdl.surface->format->Rmask,
-				sdl.surface->format->Gmask,
-				sdl.surface->format->Bmask,
-				0);
-		if (!sdl.blit.surface || (!sdl.blit.surface->flags&SDL_HWSURFACE)) {
-			if (sdl.blit.surface) {
-				SDL_FreeSurface(sdl.blit.surface);
-				sdl.blit.surface=0;
-			}
-			LOG_MSG("Failed to create ddraw surface, back to normal surface.");
-			goto dosurface;
-		}
-		switch (sdl.surface->format->BitsPerPixel) {
-		case 15:
-			retFlags = GFX_CAN_15 | GFX_SCALING | GFX_HARDWARE;
-			break;
-		case 16:
-			retFlags = GFX_CAN_16 | GFX_SCALING | GFX_HARDWARE;
-               break;
-		case 32:
-			retFlags = GFX_CAN_32 | GFX_SCALING | GFX_HARDWARE;
-               break;
-		}
-		sdl.desktop.type=SCREEN_SURFACE_DDRAW;
-		break;
+    case SCREEN_SURFACE_DDRAW:
+      if (flags & GFX_CAN_15)
+	bpp = 15;
+      if (flags & GFX_CAN_16)
+	bpp = 16;
+      if (flags & GFX_CAN_32)
+	bpp = 32;
+      if (!GFX_SetupSurfaceScaled
+	  ((sdl.desktop.doublebuf
+	    && sdl.desktop.fullscreen) ? SDL_DOUBLEBUF : 0, bpp))
+	goto dosurface;
+      sdl.blit.rect.top = sdl.clip.y;
+      sdl.blit.rect.left = sdl.clip.x;
+      sdl.blit.rect.right = sdl.clip.x + sdl.clip.w;
+      sdl.blit.rect.bottom = sdl.clip.y + sdl.clip.h;
+      sdl.blit.surface =
+	SDL_CreateRGBSurface (SDL_HWSURFACE, sdl.draw.width, sdl.draw.height,
+			      sdl.surface->format->BitsPerPixel,
+			      sdl.surface->format->Rmask,
+			      sdl.surface->format->Gmask,
+			      sdl.surface->format->Bmask, 0);
+      if (!sdl.blit.surface || (!sdl.blit.surface->flags & SDL_HWSURFACE))
+	{
+	  if (sdl.blit.surface)
+	    {
+	      SDL_FreeSurface (sdl.blit.surface);
+	      sdl.blit.surface = 0;
+	    }
+	  LOG_MSG ("Failed to create ddraw surface, back to normal surface.");
+	  goto dosurface;
+	}
+      switch (sdl.surface->format->BitsPerPixel)
+	{
+	case 15:
+	  retFlags = GFX_CAN_15 | GFX_SCALING | GFX_HARDWARE;
+	  break;
+	case 16:
+	  retFlags = GFX_CAN_16 | GFX_SCALING | GFX_HARDWARE;
+	  break;
+	case 32:
+	  retFlags = GFX_CAN_32 | GFX_SCALING | GFX_HARDWARE;
+	  break;
+	}
+      sdl.desktop.type = SCREEN_SURFACE_DDRAW;
+      break;
 #endif
-	case SCREEN_OVERLAY:
-		if (sdl.overlay) {
-			SDL_FreeYUVOverlay(sdl.overlay);
-			sdl.overlay=0;
-		}
-		if (!(flags&GFX_CAN_32) || (flags & GFX_RGBONLY)) goto dosurface;
-		if (!GFX_SetupSurfaceScaled(0,0)) goto dosurface;
-		sdl.overlay=SDL_CreateYUVOverlay(width*2,height,SDL_UYVY_OVERLAY,sdl.surface);
-		if (!sdl.overlay) {
-			LOG_MSG("SDL:Failed to create overlay, switching back to surface");
-			goto dosurface;
-		}
-		sdl.desktop.type=SCREEN_OVERLAY;
-		retFlags = GFX_CAN_32 | GFX_SCALING | GFX_HARDWARE;
-		break;
-#if C_OPENGL
-	case SCREEN_OPENGL:
+    case SCREEN_OVERLAY:
+      if (sdl.overlay)
+	{
+	  SDL_FreeYUVOverlay (sdl.overlay);
+	  sdl.overlay = 0;
+	}
+      if (!(flags & GFX_CAN_32) || (flags & GFX_RGBONLY))
+	goto dosurface;
+      if (!GFX_SetupSurfaceScaled (0, 0))
+	goto dosurface;
+      sdl.overlay =
+	SDL_CreateYUVOverlay (width * 2, height, SDL_UYVY_OVERLAY,
+			      sdl.surface);
+      if (!sdl.overlay)
 	{
-		if (sdl.opengl.framebuf) {
+	  LOG_MSG ("SDL:Failed to create overlay, switching back to surface");
+	  goto dosurface;
+	}
+      sdl.desktop.type = SCREEN_OVERLAY;
+      retFlags = GFX_CAN_32 | GFX_SCALING | GFX_HARDWARE;
+      break;
+#if C_OPENGL
+    case SCREEN_OPENGL:
+      {
+	if (sdl.opengl.framebuf)
+	  {
 #if defined(NVIDIA_PixelDataRange)
-			if (sdl.opengl.pixel_data_range) db_glFreeMemoryNV(sdl.opengl.framebuf);
-			else
-#endif
-			free(sdl.opengl.framebuf);
-		}
-		sdl.opengl.framebuf=0;
-		if (!(flags&GFX_CAN_32) || (flags & GFX_RGBONLY)) goto dosurface;
-		int texsize=2 << int_log2(width > height ? width : height);
-		if (texsize>sdl.opengl.max_texsize) {
-			LOG_MSG("SDL:OPENGL:No support for texturesize of %d, falling back to surface",texsize);
-			goto dosurface;
-		}
-		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
+	    if (sdl.opengl.pixel_data_range)
+	      db_glFreeMemoryNV (sdl.opengl.framebuf);
+	    else
+#endif
+	      free (sdl.opengl.framebuf);
+	  }
+	sdl.opengl.framebuf = 0;
+	if (!(flags & GFX_CAN_32) || (flags & GFX_RGBONLY))
+	  goto dosurface;
+	int texsize = 2 << int_log2 (width > height ? width : height);
+	if (texsize > sdl.opengl.max_texsize)
+	  {
+	    LOG_MSG
+	      ("SDL:OPENGL:No support for texturesize of %d, falling back to surface",
+	       texsize);
+	    goto dosurface;
+	  }
+	SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
 #if defined (WIN32) && SDL_VERSION_ATLEAST(1, 2, 11)
-		SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, 0 );
+	SDL_GL_SetAttribute (SDL_GL_SWAP_CONTROL, 0);
 #endif
-		GFX_SetupSurfaceScaled(SDL_OPENGL,0);
-		if (!sdl.surface || sdl.surface->format->BitsPerPixel<15) {
-			LOG_MSG("SDL:OPENGL:Can't open drawing surface, are you running in 16bpp(or higher) mode?");
-			goto dosurface;
-		}
-		/* Create the texture and display list */
+	GFX_SetupSurfaceScaled (SDL_OPENGL, 0);
+	if (!sdl.surface || sdl.surface->format->BitsPerPixel < 15)
+	  {
+	    LOG_MSG
+	      ("SDL:OPENGL:Can't open drawing surface, are you running in 16bpp(or higher) mode?");
+	    goto dosurface;
+	  }
+	/* Create the texture and display list */
 #if defined(NVIDIA_PixelDataRange)
-		if (sdl.opengl.pixel_data_range) {
-			sdl.opengl.framebuf=db_glAllocateMemoryNV(width*height*4,0.0,1.0,1.0);
-			glPixelDataRangeNV(GL_WRITE_PIXEL_DATA_RANGE_NV,width*height*4,sdl.opengl.framebuf);
-			glEnableClientState(GL_WRITE_PIXEL_DATA_RANGE_NV);
-		} else {
+	if (sdl.opengl.pixel_data_range)
+	  {
+	    sdl.opengl.framebuf =
+	      db_glAllocateMemoryNV (width * height * 4, 0.0, 1.0, 1.0);
+	    glPixelDataRangeNV (GL_WRITE_PIXEL_DATA_RANGE_NV,
+				width * height * 4, sdl.opengl.framebuf);
+	    glEnableClientState (GL_WRITE_PIXEL_DATA_RANGE_NV);
+	  }
+	else
+	  {
 #else
-		{
+	{
 #endif
-			sdl.opengl.framebuf=malloc(width*height*4);		//32 bit color
-		}
-		sdl.opengl.pitch=width*4;
-		glViewport(sdl.clip.x,sdl.clip.y,sdl.clip.w,sdl.clip.h);
-		glMatrixMode (GL_PROJECTION);
-		glDeleteTextures(1,&sdl.opengl.texture);
- 		glGenTextures(1,&sdl.opengl.texture);
-		glBindTexture(GL_TEXTURE_2D,sdl.opengl.texture);
-		// No borders
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
-		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
-		if (sdl.opengl.bilinear) {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-		} else {
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-		}
-
-		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texsize, texsize, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, 0);
-
-		glClearColor (0.0, 0.0, 0.0, 1.0);
-		glClear(GL_COLOR_BUFFER_BIT);
-		SDL_GL_SwapBuffers();
-		glClear(GL_COLOR_BUFFER_BIT);
-		glShadeModel (GL_FLAT);
-		glDisable (GL_DEPTH_TEST);
-		glDisable (GL_LIGHTING);
-		glDisable(GL_CULL_FACE);
-		glEnable(GL_TEXTURE_2D);
-		glMatrixMode (GL_MODELVIEW);
-		glLoadIdentity ();
-
-		GLfloat tex_width=((GLfloat)(width)/(GLfloat)texsize);
-		GLfloat tex_height=((GLfloat)(height)/(GLfloat)texsize);
-
-		if (glIsList(sdl.opengl.displaylist)) glDeleteLists(sdl.opengl.displaylist, 1);
-		sdl.opengl.displaylist = glGenLists(1);
-		glNewList(sdl.opengl.displaylist, GL_COMPILE);
-		glBindTexture(GL_TEXTURE_2D, sdl.opengl.texture);
-		glBegin(GL_QUADS);
-		// lower left
-		glTexCoord2f(0,tex_height); glVertex2f(-1.0f,-1.0f);
-		// lower right
-		glTexCoord2f(tex_width,tex_height); glVertex2f(1.0f, -1.0f);
-		// upper right
-		glTexCoord2f(tex_width,0); glVertex2f(1.0f, 1.0f);
-		// upper left
-		glTexCoord2f(0,0); glVertex2f(-1.0f, 1.0f);
-		glEnd();
-		glEndList();
-		sdl.desktop.type=SCREEN_OPENGL;
-		retFlags = GFX_CAN_32 | GFX_SCALING;
+	  sdl.opengl.framebuf = malloc (width * height * 4);	//32 bit color
+	}
+	sdl.opengl.pitch = width * 4;
+	glViewport (sdl.clip.x, sdl.clip.y, sdl.clip.w, sdl.clip.h);
+	glMatrixMode (GL_PROJECTION);
+	glDeleteTextures (1, &sdl.opengl.texture);
+	glGenTextures (1, &sdl.opengl.texture);
+	glBindTexture (GL_TEXTURE_2D, sdl.opengl.texture);
+	// No borders
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+	if (sdl.opengl.bilinear)
+	  {
+	    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+	    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+	  }
+	else
+	  {
+	    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
+			     GL_NEAREST);
+	    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
+			     GL_NEAREST);
+	  }
+
+	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, texsize, texsize, 0,
+		      GL_BGRA_EXT, GL_UNSIGNED_BYTE, 0);
+
+	glClearColor (0.0, 0.0, 0.0, 1.0);
+	glClear (GL_COLOR_BUFFER_BIT);
+	SDL_GL_SwapBuffers ();
+	glClear (GL_COLOR_BUFFER_BIT);
+	glShadeModel (GL_FLAT);
+	glDisable (GL_DEPTH_TEST);
+	glDisable (GL_LIGHTING);
+	glDisable (GL_CULL_FACE);
+	glEnable (GL_TEXTURE_2D);
+	glMatrixMode (GL_MODELVIEW);
+	glLoadIdentity ();
+
+	GLfloat tex_width = ((GLfloat) (width) / (GLfloat) texsize);
+	GLfloat tex_height = ((GLfloat) (height) / (GLfloat) texsize);
+
+	if (glIsList (sdl.opengl.displaylist))
+	  glDeleteLists (sdl.opengl.displaylist, 1);
+	sdl.opengl.displaylist = glGenLists (1);
+	glNewList (sdl.opengl.displaylist, GL_COMPILE);
+	glBindTexture (GL_TEXTURE_2D, sdl.opengl.texture);
+	glBegin (GL_QUADS);
+	// lower left
+	glTexCoord2f (0, tex_height);
+	glVertex2f (-1.0f, -1.0f);
+	// lower right
+	glTexCoord2f (tex_width, tex_height);
+	glVertex2f (1.0f, -1.0f);
+	// upper right
+	glTexCoord2f (tex_width, 0);
+	glVertex2f (1.0f, 1.0f);
+	// upper left
+	glTexCoord2f (0, 0);
+	glVertex2f (-1.0f, 1.0f);
+	glEnd ();
+	glEndList ();
+	sdl.desktop.type = SCREEN_OPENGL;
+	retFlags = GFX_CAN_32 | GFX_SCALING;
 #if defined(NVIDIA_PixelDataRange)
-		if (sdl.opengl.pixel_data_range)
-			retFlags |= GFX_HARDWARE;
+	if (sdl.opengl.pixel_data_range)
+	  retFlags |= GFX_HARDWARE;
 #endif
 	break;
-		}//OPENGL
-#endif	//C_OPENGL
-	default:
-		goto dosurface;
-		break;
-	}//CASE
-	if (retFlags)
-		GFX_Start();
-	if (!sdl.mouse.autoenable) SDL_ShowCursor(sdl.mouse.autolock?SDL_DISABLE:SDL_ENABLE);
-	return retFlags;
-}
-
-void GFX_CaptureMouse(void) {
-	sdl.mouse.locked=!sdl.mouse.locked;
-	if (sdl.mouse.locked) {
-		SDL_WM_GrabInput(SDL_GRAB_ON);
-		SDL_ShowCursor(SDL_DISABLE);
-	} else {
-		SDL_WM_GrabInput(SDL_GRAB_OFF);
-		if (sdl.mouse.autoenable || !sdl.mouse.autolock) SDL_ShowCursor(SDL_ENABLE);
-	}
-        mouselocked=sdl.mouse.locked;
-}
-
-bool mouselocked; //Global variable for mapper
-static void CaptureMouse(bool pressed) {
-	if (!pressed)
-		return;
-	GFX_CaptureMouse();
-}
-
-void GFX_SwitchFullScreen(void) {
-	sdl.desktop.fullscreen=!sdl.desktop.fullscreen;
-	if (sdl.desktop.fullscreen) {
-		if (!sdl.mouse.locked) GFX_CaptureMouse();
-	} else {
-		if (sdl.mouse.locked) GFX_CaptureMouse();
-	}
-	GFX_ResetScreen();
-}
-
-static void SwitchFullScreen(bool pressed) {
-	if (!pressed)
-		return;
-	GFX_SwitchFullScreen();
-}
-
-
-bool GFX_StartUpdate(Bit8u * & pixels,Bitu & pitch) {
-	if (!sdl.active || sdl.updating)
-		return false;
-	switch (sdl.desktop.type) {
-	case SCREEN_SURFACE:
-		if (sdl.blit.surface) {
-			if (SDL_MUSTLOCK(sdl.blit.surface) && SDL_LockSurface(sdl.blit.surface))
-				return false;
-			pixels=(Bit8u *)sdl.blit.surface->pixels;
-			pitch=sdl.blit.surface->pitch;
-		} else {
-			if (SDL_MUSTLOCK(sdl.surface) && SDL_LockSurface(sdl.surface))
-				return false;
-			pixels=(Bit8u *)sdl.surface->pixels;
-			pixels+=sdl.clip.y*sdl.surface->pitch;
-			pixels+=sdl.clip.x*sdl.surface->format->BytesPerPixel;
-			pitch=sdl.surface->pitch;
-		}
-		sdl.updating=true;
-		return true;
+      }				//OPENGL
+#endif //C_OPENGL
+    default:
+      goto dosurface;
+      break;
+    }				//CASE
+  if (retFlags)
+    GFX_Start ();
+  if (!sdl.mouse.autoenable)
+    SDL_ShowCursor (sdl.mouse.autolock ? SDL_DISABLE : SDL_ENABLE);
+  return retFlags;
+}
+
+void
+GFX_CaptureMouse (void)
+{
+  sdl.mouse.locked = !sdl.mouse.locked;
+  if (sdl.mouse.locked)
+    {
+      SDL_WM_GrabInput (SDL_GRAB_ON);
+      SDL_ShowCursor (SDL_DISABLE);
+    }
+  else
+    {
+      SDL_WM_GrabInput (SDL_GRAB_OFF);
+      if (sdl.mouse.autoenable || !sdl.mouse.autolock)
+	SDL_ShowCursor (SDL_ENABLE);
+    }
+  mouselocked = sdl.mouse.locked;
+}
+
+bool mouselocked;		//Global variable for mapper
+static void
+CaptureMouse (bool pressed)
+{
+  if (!pressed)
+    return;
+  GFX_CaptureMouse ();
+}
+
+void
+GFX_SwitchFullScreen (void)
+{
+  sdl.desktop.fullscreen = !sdl.desktop.fullscreen;
+  if (sdl.desktop.fullscreen)
+    {
+      if (!sdl.mouse.locked)
+	GFX_CaptureMouse ();
+    }
+  else
+    {
+      if (sdl.mouse.locked)
+	GFX_CaptureMouse ();
+    }
+  GFX_ResetScreen ();
+}
+
+static void
+SwitchFullScreen (bool pressed)
+{
+  if (!pressed)
+    return;
+  GFX_SwitchFullScreen ();
+}
+
+
+bool
+GFX_StartUpdate (Bit8u * &pixels, Bitu & pitch)
+{
+  if (!sdl.active || sdl.updating)
+    return false;
+  switch (sdl.desktop.type)
+    {
+    case SCREEN_SURFACE:
+      if (sdl.blit.surface)
+	{
+	  if (SDL_MUSTLOCK (sdl.blit.surface)
+	      && SDL_LockSurface (sdl.blit.surface))
+	    return false;
+	  pixels = (Bit8u *) sdl.blit.surface->pixels;
+	  pitch = sdl.blit.surface->pitch;
+	}
+      else
+	{
+	  if (SDL_MUSTLOCK (sdl.surface) && SDL_LockSurface (sdl.surface))
+	    return false;
+	  pixels = (Bit8u *) sdl.surface->pixels;
+	  pixels += sdl.clip.y * sdl.surface->pitch;
+	  pixels += sdl.clip.x * sdl.surface->format->BytesPerPixel;
+	  pitch = sdl.surface->pitch;
+	}
+      sdl.updating = true;
+      return true;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	case SCREEN_SURFACE_DDRAW:
-		if (SDL_LockSurface(sdl.blit.surface)) {
-//			LOG_MSG("SDL Lock failed");
-			return false;
-		}
-		pixels=(Bit8u *)sdl.blit.surface->pixels;
-		pitch=sdl.blit.surface->pitch;
-		sdl.updating=true;
-		return true;
-#endif
-	case SCREEN_OVERLAY:
-		SDL_LockYUVOverlay(sdl.overlay);
-		pixels=(Bit8u *)*(sdl.overlay->pixels);
-		pitch=*(sdl.overlay->pitches);
-		sdl.updating=true;
-		return true;
-#if C_OPENGL
-	case SCREEN_OPENGL:
-		pixels=(Bit8u *)sdl.opengl.framebuf;
-		pitch=sdl.opengl.pitch;
-		sdl.updating=true;
-		return true;
-#endif
-	default:
-		break;
+    case SCREEN_SURFACE_DDRAW:
+      if (SDL_LockSurface (sdl.blit.surface))
+	{
+//                      LOG_MSG("SDL Lock failed");
+	  return false;
 	}
-	return false;
+      pixels = (Bit8u *) sdl.blit.surface->pixels;
+      pitch = sdl.blit.surface->pitch;
+      sdl.updating = true;
+      return true;
+#endif
+    case SCREEN_OVERLAY:
+      SDL_LockYUVOverlay (sdl.overlay);
+      pixels = (Bit8u *) * (sdl.overlay->pixels);
+      pitch = *(sdl.overlay->pitches);
+      sdl.updating = true;
+      return true;
+#if C_OPENGL
+    case SCREEN_OPENGL:
+      pixels = (Bit8u *) sdl.opengl.framebuf;
+      pitch = sdl.opengl.pitch;
+      sdl.updating = true;
+      return true;
+#endif
+    default:
+      break;
+    }
+  return false;
 }
 
 
-void GFX_EndUpdate( const Bit16u *changedLines ) {
+void
+GFX_EndUpdate (const Bit16u * changedLines)
+{
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	int ret;
-#endif
-	if (!sdl.updating)
-		return;
-	sdl.updating=false;
-	switch (sdl.desktop.type) {
-	case SCREEN_SURFACE:
-		if (SDL_MUSTLOCK(sdl.surface)) {
-			if (sdl.blit.surface) {
-				SDL_UnlockSurface(sdl.blit.surface);
-				int Blit = SDL_BlitSurface( sdl.blit.surface, 0, sdl.surface, &sdl.clip );
-				LOG(LOG_MISC,LOG_WARN)("BlitSurface returned %d",Blit);
-			} else {
-				SDL_UnlockSurface(sdl.surface);
-			}
-			SDL_Flip(sdl.surface);
-		} else if (changedLines) {
-			Bitu y = 0, index = 0, rectCount = 0;
-			while (y < sdl.draw.height) {
-				if (!(index & 1)) {
-					y += changedLines[index];
-				} else {
-					SDL_Rect *rect = &sdl.updateRects[rectCount++];
-					rect->x = sdl.clip.x;
-					rect->y = sdl.clip.y + y;
-					rect->w = (Bit16u)sdl.draw.width;
-					rect->h = changedLines[index];
-#if 0
-					if (rect->h + rect->y > sdl.surface->h) {
-						LOG_MSG("WTF %d +  %d  >%d",rect->h,rect->y,sdl.surface->h);
-					}
+  int ret;
 #endif
-					y += changedLines[index];
-				}
-				index++;
-			}
-			if (rectCount)
-				SDL_UpdateRects( sdl.surface, rectCount, sdl.updateRects );
+  if (!sdl.updating)
+    return;
+  sdl.updating = false;
+  switch (sdl.desktop.type)
+    {
+    case SCREEN_SURFACE:
+      if (SDL_MUSTLOCK (sdl.surface))
+	{
+	  if (sdl.blit.surface)
+	    {
+	      SDL_UnlockSurface (sdl.blit.surface);
+	      int Blit =
+		SDL_BlitSurface (sdl.blit.surface, 0, sdl.surface, &sdl.clip);
+	      LOG (LOG_MISC, LOG_WARN) ("BlitSurface returned %d", Blit);
+	    }
+	  else
+	    {
+	      SDL_UnlockSurface (sdl.surface);
+	    }
+	  SDL_Flip (sdl.surface);
+	}
+      else if (changedLines)
+	{
+	  Bitu y = 0, index = 0, rectCount = 0;
+	  while (y < sdl.draw.height)
+	    {
+	      if (!(index & 1))
+		{
+		  y += changedLines[index];
 		}
-		break;
+	      else
+		{
+		  SDL_Rect *rect = &sdl.updateRects[rectCount++];
+		  rect->x = sdl.clip.x;
+		  rect->y = sdl.clip.y + y;
+		  rect->w = (Bit16u) sdl.draw.width;
+		  rect->h = changedLines[index];
+#if 0
+		  if (rect->h + rect->y > sdl.surface->h)
+		    {
+		      LOG_MSG ("WTF %d +  %d  >%d", rect->h, rect->y,
+			       sdl.surface->h);
+		    }
+#endif
+		  y += changedLines[index];
+		}
+	      index++;
+	    }
+	  if (rectCount)
+	    SDL_UpdateRects (sdl.surface, rectCount, sdl.updateRects);
+	}
+      break;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	case SCREEN_SURFACE_DDRAW:
-		SDL_UnlockSurface(sdl.blit.surface);
-		ret=IDirectDrawSurface3_Blt(
-			sdl.surface->hwdata->dd_writebuf,&sdl.blit.rect,
-			sdl.blit.surface->hwdata->dd_surface,0,
-			DDBLT_WAIT, NULL);
-		switch (ret) {
-		case DD_OK:
-			break;
-		case DDERR_SURFACELOST:
-			IDirectDrawSurface3_Restore(sdl.blit.surface->hwdata->dd_surface);
-			IDirectDrawSurface3_Restore(sdl.surface->hwdata->dd_surface);
-			break;
-		default:
-			LOG_MSG("DDRAW:Failed to blit, error %X",ret);
-		}
-		SDL_Flip(sdl.surface);
-		break;
+    case SCREEN_SURFACE_DDRAW:
+      SDL_UnlockSurface (sdl.blit.surface);
+      ret =
+	IDirectDrawSurface3_Blt (sdl.surface->hwdata->dd_writebuf,
+				 &sdl.blit.rect,
+				 sdl.blit.surface->hwdata->dd_surface, 0,
+				 DDBLT_WAIT, NULL);
+      switch (ret)
+	{
+	case DD_OK:
+	  break;
+	case DDERR_SURFACELOST:
+	  IDirectDrawSurface3_Restore (sdl.blit.surface->hwdata->dd_surface);
+	  IDirectDrawSurface3_Restore (sdl.surface->hwdata->dd_surface);
+	  break;
+	default:
+	  LOG_MSG ("DDRAW:Failed to blit, error %X", ret);
+	}
+      SDL_Flip (sdl.surface);
+      break;
 #endif
-	case SCREEN_OVERLAY:
-		SDL_UnlockYUVOverlay(sdl.overlay);
-		SDL_DisplayYUVOverlay(sdl.overlay,&sdl.clip);
-		break;
+    case SCREEN_OVERLAY:
+      GP2X_OSD(); //CAANOO
+      SDL_UnlockYUVOverlay (sdl.overlay);
+      SDL_DisplayYUVOverlay (sdl.overlay, &sdl.clip);
+      break;
 #if C_OPENGL
-	case SCREEN_OPENGL:
+    case SCREEN_OPENGL:
 #if defined(NVIDIA_PixelDataRange)
-		if (sdl.opengl.pixel_data_range) {
-            glBindTexture(GL_TEXTURE_2D, sdl.opengl.texture);
-			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
-					sdl.draw.width, sdl.draw.height, GL_BGRA_EXT,
-					GL_UNSIGNED_INT_8_8_8_8_REV, sdl.opengl.framebuf);
-			glCallList(sdl.opengl.displaylist);
-			SDL_GL_SwapBuffers();
-		} else
-#endif
-		if (changedLines) {
-			Bitu y = 0, index = 0;
-            glBindTexture(GL_TEXTURE_2D, sdl.opengl.texture);
-			while (y < sdl.draw.height) {
-				if (!(index & 1)) {
-					y += changedLines[index];
-				} else {
-					Bit8u *pixels = (Bit8u *)sdl.opengl.framebuf + y * sdl.opengl.pitch;
-					Bitu height = changedLines[index];
-					glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y,
-						sdl.draw.width, height, GL_BGRA_EXT,
-						GL_UNSIGNED_INT_8_8_8_8_REV, pixels );
-					y += height;
-				}
-				index++;
-			}
-			glCallList(sdl.opengl.displaylist);
-			SDL_GL_SwapBuffers();
-		}
-		break;
-#endif
-	default:
-		break;
+      if (sdl.opengl.pixel_data_range)
+	{
+	  glBindTexture (GL_TEXTURE_2D, sdl.opengl.texture);
+	  glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0,
+			   sdl.draw.width, sdl.draw.height, GL_BGRA_EXT,
+			   GL_UNSIGNED_INT_8_8_8_8_REV, sdl.opengl.framebuf);
+	  glCallList (sdl.opengl.displaylist);
+	  SDL_GL_SwapBuffers ();
 	}
+      else
+#endif
+      if (changedLines)
+	{
+	  Bitu y = 0, index = 0;
+	  glBindTexture (GL_TEXTURE_2D, sdl.opengl.texture);
+	  while (y < sdl.draw.height)
+	    {
+	      if (!(index & 1))
+		{
+		  y += changedLines[index];
+		}
+	      else
+		{
+		  Bit8u *pixels =
+		    (Bit8u *) sdl.opengl.framebuf + y * sdl.opengl.pitch;
+		  Bitu height = changedLines[index];
+		  glTexSubImage2D (GL_TEXTURE_2D, 0, 0, y,
+				   sdl.draw.width, height, GL_BGRA_EXT,
+				   GL_UNSIGNED_INT_8_8_8_8_REV, pixels);
+		  y += height;
+		}
+	      index++;
+	    }
+	  glCallList (sdl.opengl.displaylist);
+	  SDL_GL_SwapBuffers ();
+	}
+      break;
+#endif
+    default:
+      break;
+    }
 }
 
 
-void GFX_SetPalette(Bitu start,Bitu count,GFX_PalEntry * entries) {
-	/* I should probably not change the GFX_PalEntry :) */
-	if (sdl.surface->flags & SDL_HWPALETTE) {
-		if (!SDL_SetPalette(sdl.surface,SDL_PHYSPAL,(SDL_Color *)entries,start,count)) {
-			E_Exit("SDL:Can't set palette");
-		}
-	} else {
-		if (!SDL_SetPalette(sdl.surface,SDL_LOGPAL,(SDL_Color *)entries,start,count)) {
-			E_Exit("SDL:Can't set palette");
-		}
+void
+GFX_SetPalette (Bitu start, Bitu count, GFX_PalEntry * entries)
+{
+  /* I should probably not change the GFX_PalEntry :) */
+  if (sdl.surface->flags & SDL_HWPALETTE)
+    {
+      if (!SDL_SetPalette
+	  (sdl.surface, SDL_PHYSPAL, (SDL_Color *) entries, start, count))
+	{
+	  E_Exit ("SDL:Can't set palette");
 	}
+    }
+  else
+    {
+      if (!SDL_SetPalette
+	  (sdl.surface, SDL_LOGPAL, (SDL_Color *) entries, start, count))
+	{
+	  E_Exit ("SDL:Can't set palette");
+	}
+    }
 }
 
-Bitu GFX_GetRGB(Bit8u red,Bit8u green,Bit8u blue) {
-	switch (sdl.desktop.type) {
-	case SCREEN_SURFACE:
-	case SCREEN_SURFACE_DDRAW:
-		return SDL_MapRGB(sdl.surface->format,red,green,blue);
-	case SCREEN_OVERLAY:
-		{
-			Bit8u y =  ( 9797*(red) + 19237*(green) +  3734*(blue) ) >> 15;
-			Bit8u u =  (18492*((blue)-(y)) >> 15) + 128;
-			Bit8u v =  (23372*((red)-(y)) >> 15) + 128;
+Bitu
+GFX_GetRGB (Bit8u red, Bit8u green, Bit8u blue)
+{
+  switch (sdl.desktop.type)
+    {
+    case SCREEN_SURFACE:
+    case SCREEN_SURFACE_DDRAW:
+      return SDL_MapRGB (sdl.surface->format, red, green, blue);
+    case SCREEN_OVERLAY:
+      {
+	Bit8u y = (9797 * (red) + 19237 * (green) + 3734 * (blue)) >> 15;
+	Bit8u u = (18492 * ((blue) - (y)) >> 15) + 128;
+	Bit8u v = (23372 * ((red) - (y)) >> 15) + 128;
 #ifdef WORDS_BIGENDIAN
-			return (y << 0) | (v << 8) | (y << 16) | (u << 24);
+	return (y << 0) | (v << 8) | (y << 16) | (u << 24);
 #else
-			return (u << 0) | (y << 8) | (v << 16) | (y << 24);
+	return (u << 0) | (y << 8) | (v << 16) | (y << 24);
 #endif
-		}
-	case SCREEN_OPENGL:
-//		return ((red << 0) | (green << 8) | (blue << 16)) | (255 << 24);
-		//USE BGRA
-		return ((blue << 0) | (green << 8) | (red << 16)) | (255 << 24);
-	}
-	return 0;
-}
-
-void GFX_Stop() {
-	if (sdl.updating)
-		GFX_EndUpdate( 0 );
-	sdl.active=false;
-}
-
-void GFX_Start() {
-	sdl.active=true;
-}
-
-static void GUI_ShutDown(Section * /*sec*/) {
-	GFX_Stop();
-	if (sdl.draw.callback) (sdl.draw.callback)( GFX_CallBackStop );
-	if (sdl.mouse.locked) GFX_CaptureMouse();
-	if (sdl.desktop.fullscreen) GFX_SwitchFullScreen();
-}
-
-static void KillSwitch(bool pressed) {
-	if (!pressed)
-		return;
-	throw 1;
-}
-
-static void SetPriority(PRIORITY_LEVELS level) {
+      }
+    case SCREEN_OPENGL:
+//              return ((red << 0) | (green << 8) | (blue << 16)) | (255 << 24);
+      //USE BGRA
+      return ((blue << 0) | (green << 8) | (red << 16)) | (255 << 24);
+    }
+  return 0;
+}
+
+void
+GFX_Stop ()
+{
+  if (sdl.updating)
+    GFX_EndUpdate (0);
+  sdl.active = false;
+}
+
+void
+GFX_Start ()
+{
+  sdl.active = true;
+}
+
+static void
+GUI_ShutDown (Section * /*sec */ )
+{
+  GFX_Stop ();
+  if (sdl.draw.callback)
+    (sdl.draw.callback) (GFX_CallBackStop);
+  if (sdl.mouse.locked)
+    GFX_CaptureMouse ();
+  if (sdl.desktop.fullscreen)
+    GFX_SwitchFullScreen ();
+}
+
+static void
+KillSwitch (bool pressed)
+{
+  if (!pressed)
+    return;
+  throw 1;
+}
+
+static void
+SetPriority (PRIORITY_LEVELS level)
+{
 
 #if C_SET_PRIORITY
 // Do nothing if priorties are not the same and not root, else the highest
 // priority can not be set as users can only lower priority (not restore it)
 
-	if((sdl.priority.focus != sdl.priority.nofocus ) &&
-		(getuid()!=0) ) return;
+  if ((sdl.priority.focus != sdl.priority.nofocus) && (getuid () != 0))
+    return;
 
 #endif
-	switch (level) {
+  switch (level)
+    {
 #ifdef WIN32
-	case PRIORITY_LEVEL_PAUSE:	// if DOSBox is paused, assume idle priority
-	case PRIORITY_LEVEL_LOWEST:
-		SetPriorityClass(GetCurrentProcess(),IDLE_PRIORITY_CLASS);
-		break;
-	case PRIORITY_LEVEL_LOWER:
-		SetPriorityClass(GetCurrentProcess(),BELOW_NORMAL_PRIORITY_CLASS);
-		break;
-	case PRIORITY_LEVEL_NORMAL:
-		SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);
-		break;
-	case PRIORITY_LEVEL_HIGHER:
-		SetPriorityClass(GetCurrentProcess(),ABOVE_NORMAL_PRIORITY_CLASS);
-		break;
-	case PRIORITY_LEVEL_HIGHEST:
-		SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS);
-		break;
+    case PRIORITY_LEVEL_PAUSE:	// if DOSBox is paused, assume idle priority
+    case PRIORITY_LEVEL_LOWEST:
+      SetPriorityClass (GetCurrentProcess (), IDLE_PRIORITY_CLASS);
+      break;
+    case PRIORITY_LEVEL_LOWER:
+      SetPriorityClass (GetCurrentProcess (), BELOW_NORMAL_PRIORITY_CLASS);
+      break;
+    case PRIORITY_LEVEL_NORMAL:
+      SetPriorityClass (GetCurrentProcess (), NORMAL_PRIORITY_CLASS);
+      break;
+    case PRIORITY_LEVEL_HIGHER:
+      SetPriorityClass (GetCurrentProcess (), ABOVE_NORMAL_PRIORITY_CLASS);
+      break;
+    case PRIORITY_LEVEL_HIGHEST:
+      SetPriorityClass (GetCurrentProcess (), HIGH_PRIORITY_CLASS);
+      break;
 #elif C_SET_PRIORITY
 /* Linux use group as dosbox has mulitple threads under linux */
-	case PRIORITY_LEVEL_PAUSE:	// if DOSBox is paused, assume idle priority
-	case PRIORITY_LEVEL_LOWEST:
-		setpriority (PRIO_PGRP, 0,PRIO_MAX);
-		break;
-	case PRIORITY_LEVEL_LOWER:
-		setpriority (PRIO_PGRP, 0,PRIO_MAX-(PRIO_TOTAL/3));
-		break;
-	case PRIORITY_LEVEL_NORMAL:
-		setpriority (PRIO_PGRP, 0,PRIO_MAX-(PRIO_TOTAL/2));
-		break;
-	case PRIORITY_LEVEL_HIGHER:
-		setpriority (PRIO_PGRP, 0,PRIO_MAX-((3*PRIO_TOTAL)/5) );
-		break;
-	case PRIORITY_LEVEL_HIGHEST:
-		setpriority (PRIO_PGRP, 0,PRIO_MAX-((3*PRIO_TOTAL)/4) );
-		break;
-#endif
-	default:
-		break;
-	}
+    case PRIORITY_LEVEL_PAUSE:	// if DOSBox is paused, assume idle priority
+    case PRIORITY_LEVEL_LOWEST:
+      setpriority (PRIO_PGRP, 0, PRIO_MAX);
+      break;
+    case PRIORITY_LEVEL_LOWER:
+      setpriority (PRIO_PGRP, 0, PRIO_MAX - (PRIO_TOTAL / 3));
+      break;
+    case PRIORITY_LEVEL_NORMAL:
+      setpriority (PRIO_PGRP, 0, PRIO_MAX - (PRIO_TOTAL / 2));
+      break;
+    case PRIORITY_LEVEL_HIGHER:
+      setpriority (PRIO_PGRP, 0, PRIO_MAX - ((3 * PRIO_TOTAL) / 5));
+      break;
+    case PRIORITY_LEVEL_HIGHEST:
+      setpriority (PRIO_PGRP, 0, PRIO_MAX - ((3 * PRIO_TOTAL) / 4));
+      break;
+#endif
+    default:
+      break;
+    }
 }
 
 extern Bit8u int10_font_14[256 * 14];
-static void OutputString(Bitu x,Bitu y,const char * text,Bit32u color,Bit32u color2,SDL_Surface * output_surface) {
-	Bit32u * draw=(Bit32u*)(((Bit8u *)output_surface->pixels)+((y)*output_surface->pitch))+x;
-	while (*text) {
-		Bit8u * font=&int10_font_14[(*text)*14];
-		Bitu i,j;
-		Bit32u * draw_line=draw;
-		for (i=0;i<14;i++) {
-			Bit8u map=*font++;
-			for (j=0;j<8;j++) {
-				if (map & 0x80) *((Bit32u*)(draw_line+j))=color; else *((Bit32u*)(draw_line+j))=color2;
-				map<<=1;
-			}
-			draw_line+=output_surface->pitch/4;
-		}
-		text++;
-		draw+=8;
-	}
+static void
+OutputString (Bitu x, Bitu y, const char *text, Bit32u color, Bit32u color2,
+	      SDL_Surface * output_surface)
+{
+  Bit32u *draw =
+    (Bit32u *) (((Bit8u *) output_surface->pixels) +
+		((y) * output_surface->pitch)) + x;
+  while (*text)
+    {
+      Bit8u *font = &int10_font_14[(*text) * 14];
+      Bitu i, j;
+      Bit32u *draw_line = draw;
+      for (i = 0; i < 14; i++)
+	{
+	  Bit8u map = *font++;
+	  for (j = 0; j < 8; j++)
+	    {
+	      if (map & 0x80)
+		*((Bit32u *) (draw_line + j)) = color;
+	      else
+		*((Bit32u *) (draw_line + j)) = color2;
+	      map <<= 1;
+	    }
+	  draw_line += output_surface->pitch / 4;
+	}
+      text++;
+      draw += 8;
+    }
 }
 
-static unsigned char logo[32*32*4]= {
+static unsigned char logo[32 * 32 * 4] = {
 #include "dosbox_logo.h"
 };
+
 #include "dosbox_splash.h"
 
 //extern void UI_Run(bool);
-static void GUI_StartUp(Section * sec) {
-	sec->AddDestroyFunction(&GUI_ShutDown);
-	Section_prop * section=static_cast<Section_prop *>(sec);
-	sdl.active=false;
-	sdl.updating=false;
+static void
+GUI_StartUp (Section * sec)
+{
+  sec->AddDestroyFunction (&GUI_ShutDown);
+  Section_prop *section = static_cast < Section_prop * >(sec);
+  sdl.active = false;
+  sdl.updating = false;
 
 #if !defined(MACOSX)
-	/* Set Icon (must be done before any sdl_setvideomode call) */
-	/* But don't set it on OS X, as we use a nicer external icon there. */
+  /* Set Icon (must be done before any sdl_setvideomode call) */
+  /* But don't set it on OS X, as we use a nicer external icon there. */
 #if WORDS_BIGENDIAN
-	SDL_Surface* logos= SDL_CreateRGBSurfaceFrom((void*)logo,32,32,32,128,0xff000000,0x00ff0000,0x0000ff00,0);
+  SDL_Surface *logos =
+    SDL_CreateRGBSurfaceFrom ((void *) logo, 32, 32, 32, 128, 0xff000000,
+			      0x00ff0000, 0x0000ff00, 0);
 #else
-	SDL_Surface* logos= SDL_CreateRGBSurfaceFrom((void*)logo,32,32,32,128,0x000000ff,0x0000ff00,0x00ff0000,0);
-#endif
-	SDL_WM_SetIcon(logos,NULL);
-#endif
-
-	sdl.desktop.fullscreen=section->Get_bool("fullscreen");
-	sdl.wait_on_error=section->Get_bool("waitonerror");
-
-	Prop_multival* p=section->Get_multival("priority");
-	std::string focus = p->GetSection()->Get_string("active");
-	std::string notfocus = p->GetSection()->Get_string("inactive");
-
-	if      (focus == "lowest")  { sdl.priority.focus = PRIORITY_LEVEL_LOWEST;  }
-	else if (focus == "lower")   { sdl.priority.focus = PRIORITY_LEVEL_LOWER;   }
-	else if (focus == "normal")  { sdl.priority.focus = PRIORITY_LEVEL_NORMAL;  }
-	else if (focus == "higher")  { sdl.priority.focus = PRIORITY_LEVEL_HIGHER;  }
-	else if (focus == "highest") { sdl.priority.focus = PRIORITY_LEVEL_HIGHEST; }
-
-	if      (notfocus == "lowest")  { sdl.priority.nofocus=PRIORITY_LEVEL_LOWEST;  }
-	else if (notfocus == "lower")   { sdl.priority.nofocus=PRIORITY_LEVEL_LOWER;   }
-	else if (notfocus == "normal")  { sdl.priority.nofocus=PRIORITY_LEVEL_NORMAL;  }
-	else if (notfocus == "higher")  { sdl.priority.nofocus=PRIORITY_LEVEL_HIGHER;  }
-	else if (notfocus == "highest") { sdl.priority.nofocus=PRIORITY_LEVEL_HIGHEST; }
-	else if (notfocus == "pause")   {
-		/* we only check for pause here, because it makes no sense
-		 * for DOSBox to be paused while it has focus
-		 */
-		sdl.priority.nofocus=PRIORITY_LEVEL_PAUSE;
-	}
-
-	SetPriority(sdl.priority.focus); //Assume focus on startup
-	sdl.mouse.locked=false;
-	mouselocked=false; //Global for mapper
-	sdl.mouse.requestlock=false;
-	sdl.desktop.full.fixed=false;
-	const char* fullresolution=section->Get_string("fullresolution");
-	sdl.desktop.full.width  = 0;
-	sdl.desktop.full.height = 0;
-	if(fullresolution && *fullresolution) {
-		char res[100];
-		strncpy( res, fullresolution, sizeof( res ));
-		fullresolution = lowcase (res);//so x and X are allowed
-		if(strcmp(fullresolution,"original")) {
-			sdl.desktop.full.fixed = true;
-			char* height = const_cast<char*>(strchr(fullresolution,'x'));
-			if(height && * height) {
-				*height = 0;
-				sdl.desktop.full.height = (Bit16u)atoi(height+1);
-				sdl.desktop.full.width  = (Bit16u)atoi(res);
-			}
-		}
-	}
-
-	sdl.desktop.window.width  = 0;
-	sdl.desktop.window.height = 0;
-	const char* windowresolution=section->Get_string("windowresolution");
-	if(windowresolution && *windowresolution) {
-		char res[100];
-		strncpy( res,windowresolution, sizeof( res ));
-		windowresolution = lowcase (res);//so x and X are allowed
-		if(strcmp(windowresolution,"original")) {
-			char* height = const_cast<char*>(strchr(windowresolution,'x'));
-			if(height && *height) {
-				*height = 0;
-				sdl.desktop.window.height = (Bit16u)atoi(height+1);
-				sdl.desktop.window.width  = (Bit16u)atoi(res);
-			}
-		}
-	}
-	sdl.desktop.doublebuf=section->Get_bool("fulldouble");
-	if (!sdl.desktop.full.width) {
+  SDL_Surface *logos =
+    SDL_CreateRGBSurfaceFrom ((void *) logo, 32, 32, 32, 128, 0x000000ff,
+			      0x0000ff00, 0x00ff0000, 0);
+#endif
+  SDL_WM_SetIcon (logos, NULL);
+#endif
+
+  GP2X_MOUSE_SPEED = section->Get_int("gp2x_mouse_speed");        // Get GP2X/CAANOO parameters
+  fontcolor_front = section->Get_int("fontcolor_front");
+  fontcolor_back = section->Get_int("fontcolor_back");
+  fontcolor_frontsel = section->Get_int("fontcolor_frontsel");
+  fontcolor_backsel = section->Get_int("fontcolor_backsel"); // \GP2X/CAANOO
+
+  sdl.desktop.fullscreen = section->Get_bool ("fullscreen");
+  sdl.wait_on_error = section->Get_bool ("waitonerror");
+
+  Prop_multival *p = section->Get_multival ("priority");
+  std::string focus = p->GetSection ()->Get_string ("active");
+  std::string notfocus = p->GetSection ()->Get_string ("inactive");
+
+  if (focus == "lowest")
+    {
+      sdl.priority.focus = PRIORITY_LEVEL_LOWEST;
+    }
+  else if (focus == "lower")
+    {
+      sdl.priority.focus = PRIORITY_LEVEL_LOWER;
+    }
+  else if (focus == "normal")
+    {
+      sdl.priority.focus = PRIORITY_LEVEL_NORMAL;
+    }
+  else if (focus == "higher")
+    {
+      sdl.priority.focus = PRIORITY_LEVEL_HIGHER;
+    }
+  else if (focus == "highest")
+    {
+      sdl.priority.focus = PRIORITY_LEVEL_HIGHEST;
+    }
+
+  if (notfocus == "lowest")
+    {
+      sdl.priority.nofocus = PRIORITY_LEVEL_LOWEST;
+    }
+  else if (notfocus == "lower")
+    {
+      sdl.priority.nofocus = PRIORITY_LEVEL_LOWER;
+    }
+  else if (notfocus == "normal")
+    {
+      sdl.priority.nofocus = PRIORITY_LEVEL_NORMAL;
+    }
+  else if (notfocus == "higher")
+    {
+      sdl.priority.nofocus = PRIORITY_LEVEL_HIGHER;
+    }
+  else if (notfocus == "highest")
+    {
+      sdl.priority.nofocus = PRIORITY_LEVEL_HIGHEST;
+    }
+  else if (notfocus == "pause")
+    {
+      /* we only check for pause here, because it makes no sense
+       * for DOSBox to be paused while it has focus
+       */
+      sdl.priority.nofocus = PRIORITY_LEVEL_PAUSE;
+    }
+
+  SetPriority (sdl.priority.focus);	//Assume focus on startup
+  sdl.mouse.locked = false;
+  mouselocked = false;		//Global for mapper
+  sdl.mouse.requestlock = false;
+  sdl.desktop.full.fixed = false;
+  const char *fullresolution = section->Get_string ("fullresolution");
+  sdl.desktop.full.width = 0;
+  sdl.desktop.full.height = 0;
+  if (fullresolution && *fullresolution)
+    {
+      char res[100];
+      strncpy (res, fullresolution, sizeof (res));
+      fullresolution = lowcase (res);	//so x and X are allowed
+      if (strcmp (fullresolution, "original"))
+	{
+	  sdl.desktop.full.fixed = true;
+	  char *height = const_cast < char *>(strchr (fullresolution, 'x'));
+	  if (height && *height)
+	    {
+	      *height = 0;
+	      sdl.desktop.full.height = (Bit16u) atoi (height + 1);
+	      sdl.desktop.full.width = (Bit16u) atoi (res);
+	    }
+	}
+    }
+
+  sdl.desktop.window.width = 0;
+  sdl.desktop.window.height = 0;
+  const char *windowresolution = section->Get_string ("windowresolution");
+  if (windowresolution && *windowresolution)
+    {
+      char res[100];
+      strncpy (res, windowresolution, sizeof (res));
+      windowresolution = lowcase (res);	//so x and X are allowed
+      if (strcmp (windowresolution, "original"))
+	{
+	  char *height = const_cast < char *>(strchr (windowresolution, 'x'));
+	  if (height && *height)
+	    {
+	      *height = 0;
+	      sdl.desktop.window.height = (Bit16u) atoi (height + 1);
+	      sdl.desktop.window.width = (Bit16u) atoi (res);
+	    }
+	}
+    }
+  sdl.desktop.doublebuf = section->Get_bool ("fulldouble");
+  if (!sdl.desktop.full.width)
+    {
 #ifdef WIN32
-		sdl.desktop.full.width=(Bit16u)GetSystemMetrics(SM_CXSCREEN);
+      sdl.desktop.full.width = (Bit16u) GetSystemMetrics (SM_CXSCREEN);
 #else
-		sdl.desktop.full.width=1024;
+      sdl.desktop.full.width = 1024;
 #endif
-	}
-	if (!sdl.desktop.full.height) {
+    }
+  if (!sdl.desktop.full.height)
+    {
 #ifdef WIN32
-		sdl.desktop.full.height=(Bit16u)GetSystemMetrics(SM_CYSCREEN);
+      sdl.desktop.full.height = (Bit16u) GetSystemMetrics (SM_CYSCREEN);
 #else
-		sdl.desktop.full.height=768;
+      sdl.desktop.full.height = 768;
 #endif
-	}
-	sdl.mouse.autoenable=section->Get_bool("autolock");
-	if (!sdl.mouse.autoenable) SDL_ShowCursor(SDL_DISABLE);
-	sdl.mouse.autolock=false;
-	sdl.mouse.sensitivity=section->Get_int("sensitivity");
-	std::string output=section->Get_string("output");
-
-	/* Setup Mouse correctly if fullscreen */
-	if(sdl.desktop.fullscreen) GFX_CaptureMouse();
-
-	if (output == "surface") {
-		sdl.desktop.want_type=SCREEN_SURFACE;
+    }
+  sdl.mouse.autoenable = section->Get_bool ("autolock");
+  if (!sdl.mouse.autoenable)
+    SDL_ShowCursor (SDL_DISABLE);
+  sdl.mouse.autolock = false;
+  sdl.mouse.sensitivity = section->Get_int ("sensitivity");
+  std::string output = section->Get_string ("output");
+
+  /* Setup Mouse correctly if fullscreen */
+  if (sdl.desktop.fullscreen)
+    GFX_CaptureMouse ();
+
+  if (output == "surface")
+    {
+      sdl.desktop.want_type = SCREEN_SURFACE;
 #if (HAVE_DDRAW_H) && defined(WIN32)
-	} else if (output == "ddraw") {
-		sdl.desktop.want_type=SCREEN_SURFACE_DDRAW;
-#endif
-	} else if (output == "overlay") {
-		sdl.desktop.want_type=SCREEN_OVERLAY;
+    }
+  else if (output == "ddraw")
+    {
+      sdl.desktop.want_type = SCREEN_SURFACE_DDRAW;
+#endif
+    }
+  else if (output == "overlay")
+    {
+      sdl.desktop.want_type = SCREEN_OVERLAY;
 #if C_OPENGL
-	} else if (output == "opengl") {
-		sdl.desktop.want_type=SCREEN_OPENGL;
-		sdl.opengl.bilinear=true;
-	} else if (output == "openglnb") {
-		sdl.desktop.want_type=SCREEN_OPENGL;
-		sdl.opengl.bilinear=false;
-#endif
-	} else {
-		LOG_MSG("SDL:Unsupported output device %s, switching back to surface",output.c_str());
-		sdl.desktop.want_type=SCREEN_SURFACE;//SHOULDN'T BE POSSIBLE anymore
-	}
+    }
+  else if (output == "opengl")
+    {
+      sdl.desktop.want_type = SCREEN_OPENGL;
+      sdl.opengl.bilinear = true;
+    }
+  else if (output == "openglnb")
+    {
+      sdl.desktop.want_type = SCREEN_OPENGL;
+      sdl.opengl.bilinear = false;
+#endif
+    }
+  else
+    {
+      LOG_MSG ("SDL:Unsupported output device %s, switching back to surface",
+	       output.c_str ());
+      sdl.desktop.want_type = SCREEN_SURFACE;	//SHOULDN'T BE POSSIBLE anymore
+    }
 
-	sdl.overlay=0;
+  sdl.overlay = 0;
 #if C_OPENGL
-   if(sdl.desktop.want_type==SCREEN_OPENGL){ /* OPENGL is requested */
-	sdl.surface=SDL_SetVideoMode(640,400,0,SDL_OPENGL);
-	if (sdl.surface == NULL) {
-		LOG_MSG("Could not initialize OpenGL, switching back to surface");
-		sdl.desktop.want_type=SCREEN_SURFACE;
-	} else {
-	sdl.opengl.framebuf=0;
-	sdl.opengl.texture=0;
-	sdl.opengl.displaylist=0;
-	glGetIntegerv (GL_MAX_TEXTURE_SIZE, &sdl.opengl.max_texsize);
+  if (sdl.desktop.want_type == SCREEN_OPENGL)
+    {				/* OPENGL is requested */
+      sdl.surface = SDL_SetVideoMode (640, 400, 0, SDL_OPENGL);
+      if (sdl.surface == NULL)
+	{
+	  LOG_MSG ("Could not initialize OpenGL, switching back to surface");
+	  sdl.desktop.want_type = SCREEN_SURFACE;
+	}
+      else
+	{
+	  sdl.opengl.framebuf = 0;
+	  sdl.opengl.texture = 0;
+	  sdl.opengl.displaylist = 0;
+	  glGetIntegerv (GL_MAX_TEXTURE_SIZE, &sdl.opengl.max_texsize);
 #if defined(__WIN32__) && defined(NVIDIA_PixelDataRange)
-	glPixelDataRangeNV = (PFNGLPIXELDATARANGENVPROC) wglGetProcAddress("glPixelDataRangeNV");
-	db_glAllocateMemoryNV = (PFNWGLALLOCATEMEMORYNVPROC) wglGetProcAddress("wglAllocateMemoryNV");
-	db_glFreeMemoryNV = (PFNWGLFREEMEMORYNVPROC) wglGetProcAddress("wglFreeMemoryNV");
-#endif
-	const char * gl_ext = (const char *)glGetString (GL_EXTENSIONS);
-	if(gl_ext && *gl_ext){
-		sdl.opengl.packed_pixel=(strstr(gl_ext,"EXT_packed_pixels") > 0);
-		sdl.opengl.paletted_texture=(strstr(gl_ext,"EXT_paletted_texture") > 0);
+	  glPixelDataRangeNV =
+	    (PFNGLPIXELDATARANGENVPROC)
+	    wglGetProcAddress ("glPixelDataRangeNV");
+	  db_glAllocateMemoryNV =
+	    (PFNWGLALLOCATEMEMORYNVPROC)
+	    wglGetProcAddress ("wglAllocateMemoryNV");
+	  db_glFreeMemoryNV =
+	    (PFNWGLFREEMEMORYNVPROC) wglGetProcAddress ("wglFreeMemoryNV");
+#endif
+	  const char *gl_ext = (const char *) glGetString (GL_EXTENSIONS);
+	  if (gl_ext && *gl_ext)
+	    {
+	      sdl.opengl.packed_pixel =
+		(strstr (gl_ext, "EXT_packed_pixels") > 0);
+	      sdl.opengl.paletted_texture =
+		(strstr (gl_ext, "EXT_paletted_texture") > 0);
 #if defined(NVIDIA_PixelDataRange)
-		sdl.opengl.pixel_data_range=(strstr(gl_ext,"GL_NV_pixel_data_range") >0 ) &&
-			glPixelDataRangeNV && db_glAllocateMemoryNV && db_glFreeMemoryNV;
-		sdl.opengl.pixel_data_range = 0;
-#endif
-    	} else {
-		sdl.opengl.packed_pixel=sdl.opengl.paletted_texture=false;
-	}
-	}
-	} /* OPENGL is requested end */
-
-#endif	//OPENGL
-	/* Initialize screen for first time */
-	sdl.surface=SDL_SetVideoMode(640,400,0,0);
-	if (sdl.surface == NULL) E_Exit("Could not initialize video: %s",SDL_GetError());
-	sdl.desktop.bpp=sdl.surface->format->BitsPerPixel;
-	if (sdl.desktop.bpp==24) {
-		LOG_MSG("SDL:You are running in 24 bpp mode, this will slow down things!");
-	}
-	GFX_Stop();
-	SDL_WM_SetCaption("DOSBox",VERSION);
+	      sdl.opengl.pixel_data_range =
+		(strstr (gl_ext, "GL_NV_pixel_data_range") > 0)
+		&& glPixelDataRangeNV && db_glAllocateMemoryNV
+		&& db_glFreeMemoryNV;
+	      sdl.opengl.pixel_data_range = 0;
+#endif
+	    }
+	  else
+	    {
+	      sdl.opengl.packed_pixel = sdl.opengl.paletted_texture = false;
+	    }
+	}
+    }				/* OPENGL is requested end */
+
+#endif //OPENGL
+  /* Initialize screen for first time */
+  sdl.surface = SDL_SetVideoMode (320, 240, 16, 0); // CAANOO
+  if (sdl.surface == NULL)
+    E_Exit ("Could not initialize video: %s", SDL_GetError ());
+  sdl.desktop.bpp = sdl.surface->format->BitsPerPixel;
+  if (sdl.desktop.bpp == 24)
+    {
+      LOG_MSG
+	("SDL:You are running in 24 bpp mode, this will slow down things!");
+    }
+  GFX_Stop ();
+  SDL_WM_SetCaption ("DOSBox", VERSION);
 
 /* The endian part is intentionally disabled as somehow it produces correct results without according to rhoenie*/
 //#if SDL_BYTEORDER == SDL_BIG_ENDIAN
@@ -1164,280 +2491,497 @@
 //    Bit32u gmask = 0x00ff0000;
 //    Bit32u bmask = 0x0000ff00;
 //#else
-    Bit32u rmask = 0x000000ff;
-    Bit32u gmask = 0x0000ff00;
-    Bit32u bmask = 0x00ff0000;
+  Bit32u rmask = 0x000000ff;
+  Bit32u gmask = 0x0000ff00;
+  Bit32u bmask = 0x00ff0000;
 //#endif
 
 /* Please leave the Splash screen stuff in working order in DOSBox. We spend a lot of time making DOSBox. */
-	SDL_Surface* splash_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, 640, 400, 32, rmask, gmask, bmask, 0);
-	if (splash_surf) {
-		SDL_FillRect(splash_surf, NULL, SDL_MapRGB(splash_surf->format, 0, 0, 0));
-
-		Bit8u* tmpbufp = new Bit8u[640*400*3];
-		GIMP_IMAGE_RUN_LENGTH_DECODE(tmpbufp,gimp_image.rle_pixel_data,640*400,3);
-		for (Bitu y=0; y<400; y++) {
-
-			Bit8u* tmpbuf = tmpbufp + y*640*3;
-			Bit32u * draw=(Bit32u*)(((Bit8u *)splash_surf->pixels)+((y)*splash_surf->pitch));
-			for (Bitu x=0; x<640; x++) {
+  SDL_Surface *splash_surf =
+    SDL_CreateRGBSurface (SDL_SWSURFACE, 640, 400, 32, rmask, gmask, bmask,
+			  0);
+  if (splash_surf)
+    {
+      SDL_Rect GP2X_clip; // CAANOO
+      GP2X_clip.x=160;GP2X_clip.y=80; // CAANOO
+      GP2X_clip.w=320;GP2X_clip.h=240; // CAANOO
+      
+      SDL_FillRect (splash_surf, NULL,
+		    SDL_MapRGB (splash_surf->format, 0, 0, 0));
+
+      Bit8u *tmpbufp = new Bit8u[640 * 400 * 3];
+      GIMP_IMAGE_RUN_LENGTH_DECODE (tmpbufp, gimp_image.rle_pixel_data,
+				    640 * 400, 3);
+      for (Bitu y = 0; y < 400; y++)
+	{
+
+	  Bit8u *tmpbuf = tmpbufp + y * 640 * 3;
+	  Bit32u *draw =
+	    (Bit32u *) (((Bit8u *) splash_surf->pixels) +
+			((y) * splash_surf->pitch));
+	  for (Bitu x = 0; x < 640; x++)
+	    {
 //#if SDL_BYTEORDER == SDL_BIG_ENDIAN
-//				*draw++ = tmpbuf[x*3+2]+tmpbuf[x*3+1]*0x100+tmpbuf[x*3+0]*0x10000+0x00000000;
+//                              *draw++ = tmpbuf[x*3+2]+tmpbuf[x*3+1]*0x100+tmpbuf[x*3+0]*0x10000+0x00000000;
 //#else
-				*draw++ = tmpbuf[x*3+0]+tmpbuf[x*3+1]*0x100+tmpbuf[x*3+2]*0x10000+0x00000000;
+	      *draw++ =
+		tmpbuf[x * 3 + 0] + tmpbuf[x * 3 + 1] * 0x100 + tmpbuf[x * 3 +
+								       2] *
+		0x10000 + 0x00000000;
 //#endif
-			}
-		}
-
-		bool exit_splash = false;
+	    }
+	}
 
-		static Bitu max_splash_loop = 600;
-		static Bitu splash_fade = 100;
-		static bool use_fadeout = true;
-
-		for (Bit32u ct = 0,startticks = GetTicks();ct < max_splash_loop;ct = GetTicks()-startticks) {
-			SDL_Event evt;
-			while (SDL_PollEvent(&evt)) {
-				if (evt.type == SDL_QUIT) {
-					exit_splash = true;
-					break;
-				}
-			}
-			if (exit_splash) break;
+      bool exit_splash = false;
 
-			if (ct<1) {
-				SDL_FillRect(sdl.surface, NULL, SDL_MapRGB(sdl.surface->format, 0, 0, 0));
-				SDL_SetAlpha(splash_surf, SDL_SRCALPHA,255);
-				SDL_BlitSurface(splash_surf, NULL, sdl.surface, NULL);
-				SDL_Flip(sdl.surface);
-			} else if (ct>=max_splash_loop-splash_fade) {
-				if (use_fadeout) {
-					SDL_FillRect(sdl.surface, NULL, SDL_MapRGB(sdl.surface->format, 0, 0, 0));
-					SDL_SetAlpha(splash_surf, SDL_SRCALPHA, (Bit8u)((max_splash_loop-1-ct)*255/(splash_fade-1)));
-					SDL_BlitSurface(splash_surf, NULL, sdl.surface, NULL);
-					SDL_Flip(sdl.surface);
-				}
-			}
+      static Bitu max_splash_loop = 600;
+      static Bitu splash_fade = 100;
+      static bool use_fadeout = true;
 
+      for (Bit32u ct = 0, startticks = GetTicks (); ct < max_splash_loop;
+	   ct = GetTicks () - startticks)
+	{
+	  SDL_Event evt;
+	  while (SDL_PollEvent (&evt))
+	    {
+	      if (evt.type == SDL_QUIT)
+		{
+		  exit_splash = true;
+		  break;
 		}
-
-		if (use_fadeout) {
-			SDL_FillRect(sdl.surface, NULL, SDL_MapRGB(sdl.surface->format, 0, 0, 0));
-			SDL_Flip(sdl.surface);
+	    }
+	  if (exit_splash)
+	    break;
+
+	  if (ct < 1)
+	    {
+	      SDL_FillRect (sdl.surface, NULL,
+			    SDL_MapRGB (sdl.surface->format, 0, 0, 0));
+	      SDL_SetAlpha (splash_surf, SDL_SRCALPHA, 255);
+	      SDL_BlitSurface (splash_surf, &GP2X_clip, sdl.surface, NULL); // CAANOO
+	      SDL_Flip (sdl.surface);
+	    }
+	  else if (ct >= max_splash_loop - splash_fade)
+	    {
+	      if (use_fadeout)
+		{
+		  SDL_FillRect (sdl.surface, NULL,
+				SDL_MapRGB (sdl.surface->format, 0, 0, 0));
+		  SDL_SetAlpha (splash_surf, SDL_SRCALPHA,
+				(Bit8u) ((max_splash_loop - 1 -
+					  ct) * 255 / (splash_fade - 1)));
+		  SDL_BlitSurface (splash_surf, &GP2X_clip, sdl.surface, NULL); // CAANOO
+		  SDL_Flip (sdl.surface);
 		}
-		SDL_FreeSurface(splash_surf);
-		delete [] tmpbufp;
+	    }
 
 	}
 
-	/* Get some Event handlers */
-	MAPPER_AddHandler(KillSwitch,MK_f9,MMOD1,"shutdown","ShutDown");
-	MAPPER_AddHandler(CaptureMouse,MK_f10,MMOD1,"capmouse","Cap Mouse");
-	MAPPER_AddHandler(SwitchFullScreen,MK_return,MMOD2,"fullscr","Fullscreen");
+      if (use_fadeout)
+	{
+	  SDL_FillRect (sdl.surface, NULL,
+			SDL_MapRGB (sdl.surface->format, 0, 0, 0));
+	  SDL_Flip (sdl.surface);
+	}
+      SDL_FreeSurface (splash_surf);
+      delete[]tmpbufp;
+
+    }
+
+  /* Get some Event handlers */
+  MAPPER_AddHandler (KillSwitch, MK_f9, MMOD1, "shutdown", "ShutDown");
+  MAPPER_AddHandler (CaptureMouse, MK_f10, MMOD1, "capmouse", "Cap Mouse");
+  MAPPER_AddHandler (SwitchFullScreen, MK_return, MMOD2, "fullscr",
+		     "Fullscreen");
+  
+	MAPPER_AddHandler(GP2X_Debug_Toggle,MK_f3,MMOD1,"g2debug","debug GP2X");  //CAANOO
+    MAPPER_AddHandler(GP2X_VirtualKeyboard_Toggle,MK_f3,MMOD1,"g2virtkey","toggle keyboard emu GP2X"); //CAANOO
+	MAPPER_AddHandler(GP2X_EmuMouseToggle,MK_f4,MMOD1,"g2mouse","toggle mouse emu GP2X"); //CAANOO
+	MAPPER_AddHandler(GP2X_NoClick,MK_f5,MMOD1,"noclick","no clicks GP2X"); //CAANOO
+    MAPPER_AddHandler(GP2X_LeftClick,MK_f6,MMOD1,"leftclick","send left click GP2X"); //CAANOO
+	MAPPER_AddHandler(GP2X_RightClick,MK_f7,MMOD1,"rightclick","send right click GP2X"); //CAANOO
+         
+         
 #if C_DEBUG
-	/* Pause binds with activate-debugger */
+  /* Pause binds with activate-debugger */
 #else
-	MAPPER_AddHandler(&PauseDOSBox, MK_pause, MMOD2, "pause", "Pause");
+  MAPPER_AddHandler (&PauseDOSBox, MK_pause, MMOD2, "pause", "Pause");
 #endif
-	/* Get Keyboard state of numlock and capslock */
-	SDLMod keystate = SDL_GetModState();
-	if(keystate&KMOD_NUM) startup_state_numlock = true;
-	if(keystate&KMOD_CAPS) startup_state_capslock = true;
-}
-
-void Mouse_AutoLock(bool enable) {
-	sdl.mouse.autolock=enable;
-	if (sdl.mouse.autoenable) sdl.mouse.requestlock=enable;
-	else {
-		SDL_ShowCursor(enable?SDL_DISABLE:SDL_ENABLE);
-		sdl.mouse.requestlock=false;
+  /* Get Keyboard state of numlock and capslock */
+  SDLMod keystate = SDL_GetModState ();
+  if (keystate & KMOD_NUM)
+    startup_state_numlock = true;
+  if (keystate & KMOD_CAPS)
+    startup_state_capslock = true;
+}
+
+void
+Mouse_AutoLock (bool enable)
+{
+  sdl.mouse.autolock = enable;
+  if (sdl.mouse.autoenable)
+    sdl.mouse.requestlock = enable;
+  else
+    {
+      SDL_ShowCursor (enable ? SDL_DISABLE : SDL_ENABLE);
+      sdl.mouse.requestlock = false;
+    }
+}
+
+static void
+HandleMouseMotion (SDL_MouseMotionEvent * motion)
+{
+//GP2X  
+//  printf("mouse: %d %d %d\n",motion->y,SDL_GetVideoSurface()->h, sdl.clip.y);
+  if (sdl.mouse.locked || !sdl.mouse.autoenable)
+    Mouse_CursorMovedFixed((float)(motion->x-sdl.clip.x)/(float)(sdl.clip.w-1), (float)(motion->y-sdl.clip.y)/(float)(sdl.clip.h-1), sdl.mouse.locked);
+/*
+    Mouse_CursorMoved ((float) motion->xrel * sdl.mouse.sensitivity / 100.0f,
+		       (float) motion->yrel * sdl.mouse.sensitivity / 100.0f,
+		       (float) (motion->x - sdl.clip.x) / (sdl.clip.w -
+							   1) *
+		       sdl.mouse.sensitivity / 100.0f,
+		       (float) (motion->y - sdl.clip.y) / (sdl.clip.h -
+							   1) *
+		       sdl.mouse.sensitivity / 100.0f, sdl.mouse.locked); */
+}
+
+static void
+HandleMouseButton (SDL_MouseButtonEvent * button)
+{
+  if( SDL_JoystickGetButton(psp_sdl_joy, BTN_TACT) == SDL_PRESSED &&
+      button->button == SDL_BUTTON_LEFT)
+    button->button=SDL_BUTTON_RIGHT; // GP2X/CAANOO
+
+  switch (button->state)
+    {
+    case SDL_PRESSED:
+      if (sdl.mouse.requestlock && !sdl.mouse.locked)
+	{
+	  GFX_CaptureMouse ();
+	  // Dont pass klick to mouse handler
+	  break;
 	}
-}
-
-static void HandleMouseMotion(SDL_MouseMotionEvent * motion) {
-	if (sdl.mouse.locked || !sdl.mouse.autoenable)
-		Mouse_CursorMoved((float)motion->xrel*sdl.mouse.sensitivity/100.0f,
-						  (float)motion->yrel*sdl.mouse.sensitivity/100.0f,
-						  (float)(motion->x-sdl.clip.x)/(sdl.clip.w-1)*sdl.mouse.sensitivity/100.0f,
-						  (float)(motion->y-sdl.clip.y)/(sdl.clip.h-1)*sdl.mouse.sensitivity/100.0f,
-						  sdl.mouse.locked);
-}
-
-static void HandleMouseButton(SDL_MouseButtonEvent * button) {
-	switch (button->state) {
-	case SDL_PRESSED:
-		if (sdl.mouse.requestlock && !sdl.mouse.locked) {
-			GFX_CaptureMouse();
-			// Dont pass klick to mouse handler
-			break;
-		}
-		if (!sdl.mouse.autoenable && sdl.mouse.autolock && button->button == SDL_BUTTON_MIDDLE) {
-			GFX_CaptureMouse();
-			break;
-		}
-		switch (button->button) {
-		case SDL_BUTTON_LEFT:
-			Mouse_ButtonPressed(0);
-			break;
-		case SDL_BUTTON_RIGHT:
-			Mouse_ButtonPressed(1);
-			break;
-		case SDL_BUTTON_MIDDLE:
-			Mouse_ButtonPressed(2);
-			break;
-		}
-		break;
-	case SDL_RELEASED:
-		switch (button->button) {
-		case SDL_BUTTON_LEFT:
-			Mouse_ButtonReleased(0);
-			break;
-		case SDL_BUTTON_RIGHT:
-			Mouse_ButtonReleased(1);
-			break;
-		case SDL_BUTTON_MIDDLE:
-			Mouse_ButtonReleased(2);
-			break;
-		}
-		break;
+      if (!sdl.mouse.autoenable && sdl.mouse.autolock
+	  && button->button == SDL_BUTTON_MIDDLE)
+	{
+	  GFX_CaptureMouse ();
+	  break;
 	}
-}
-
-void GFX_LosingFocus(void) {
-	sdl.laltstate=SDL_KEYUP;
-	sdl.raltstate=SDL_KEYUP;
-	MAPPER_LosingFocus();
-}
-
-void GFX_Events() {
-	SDL_Event event;
+      switch (button->button)
+	{
+	case SDL_BUTTON_LEFT:
+			// GP2X hack - move on click
+			Mouse_CursorMovedFixed((float)button->x/(float)SDL_GetVideoSurface()->w, (float)button->y/(float)SDL_GetVideoSurface()->h, sdl.mouse.locked);
+			if(!gp2x_noclick) Mouse_ButtonPressed(0); // \GP2X  
+    Mouse_ButtonPressed (0);
+	  break;
+	case SDL_BUTTON_RIGHT:
+    Mouse_CursorMovedFixed((float)button->x/(float)SDL_GetVideoSurface()->w, (float)button->y/(float)SDL_GetVideoSurface()->h, sdl.mouse.locked);     // GP2X
+	  Mouse_ButtonPressed (1);
+	  break;
+	case SDL_BUTTON_MIDDLE:
+	  Mouse_ButtonPressed (2);
+	  break;
+	}
+      break;
+    case SDL_RELEASED:
+      switch (button->button)
+	{
+	case SDL_BUTTON_LEFT:
+    // GP2X
+            Mouse_CursorMovedFixed((float)button->x/(float)SDL_GetVideoSurface()->w, (float)button->y/(float)SDL_GetVideoSurface()->h, sdl.mouse.locked);
+			if(!gp2x_noclick) Mouse_ButtonReleased(0); // \GP2X        
+    Mouse_ButtonReleased (0);
+	  break;
+	case SDL_BUTTON_RIGHT:
+    Mouse_CursorMovedFixed((float)button->x/(float)SDL_GetVideoSurface()->w, (float)button->y/(float)SDL_GetVideoSurface()->h, sdl.mouse.locked);     // GP2X
+    Mouse_ButtonReleased (1);
+	  break;
+	case SDL_BUTTON_MIDDLE:
+	  Mouse_ButtonReleased (2);
+	  break;
+	}
+      break;
+    }
+}
+
+void
+GFX_LosingFocus (void)
+{
+  sdl.laltstate = SDL_KEYUP;
+  sdl.raltstate = SDL_KEYUP;
+  MAPPER_LosingFocus ();
+}
+
+void
+GFX_Events ()
+{
+  SDL_Event event;
 #if defined (REDUCE_JOYSTICK_POLLING)
-	static int poll_delay=0;
-	int time=GetTicks();
-	if (time-poll_delay>20) {
-		poll_delay=time;
-		if (sdl.num_joysticks>0) SDL_JoystickUpdate();
-		MAPPER_UpdateJoysticks();
-	}
-#endif
-	while (SDL_PollEvent(&event)) {
-		switch (event.type) {
-		case SDL_ACTIVEEVENT:
-			if (event.active.state & SDL_APPINPUTFOCUS) {
-				if (event.active.gain) {
-					if (sdl.desktop.fullscreen && !sdl.mouse.locked)
-						GFX_CaptureMouse();
-					SetPriority(sdl.priority.focus);
-					CPU_Disable_SkipAutoAdjust();
-				} else {
-					if (sdl.mouse.locked) {
+  static int poll_delay = 0;
+  int time = GetTicks ();
+  if (time - poll_delay > 20)
+    {
+      poll_delay = time;
+      if (sdl.num_joysticks > 0)
+	SDL_JoystickUpdate ();
+      MAPPER_UpdateJoysticks ();
+    }
+#endif
+  Caanoo_UpdateAnalog(); //CAANOO
+  while (SDL_PollEvent (&event))
+    {
+      switch (event.type)
+	{
+	case SDL_ACTIVEEVENT:
+	  if (event.active.state & SDL_APPINPUTFOCUS)
+	    {
+	      if (event.active.gain)
+		{
+		  if (sdl.desktop.fullscreen && !sdl.mouse.locked)
+		    GFX_CaptureMouse ();
+		  SetPriority (sdl.priority.focus);
+		  CPU_Disable_SkipAutoAdjust ();
+		}
+	      else
+		{
+		  if (sdl.mouse.locked)
+		    {
 #ifdef WIN32
-						if (sdl.desktop.fullscreen) {
-							VGA_KillDrawing();
-							sdl.desktop.fullscreen=false;
-							GFX_ResetScreen();
-						}
-#endif
-						GFX_CaptureMouse();
-					}
-					SetPriority(sdl.priority.nofocus);
-					GFX_LosingFocus();
-					CPU_Enable_SkipAutoAdjust();
+		      if (sdl.desktop.fullscreen)
+			{
+			  VGA_KillDrawing ();
+			  sdl.desktop.fullscreen = false;
+			  GFX_ResetScreen ();
+			}
+#endif
+		      GFX_CaptureMouse ();
+		    }
+		  SetPriority (sdl.priority.nofocus);
+		  GFX_LosingFocus ();
+		  CPU_Enable_SkipAutoAdjust ();
+		}
+	    }
+
+	  /* Non-focus priority is set to pause; check to see if we've lost window or input focus
+	   * i.e. has the window been minimised or made inactive?
+	   */
+	  if (sdl.priority.nofocus == PRIORITY_LEVEL_PAUSE)
+	    {
+	      if ((event.active.state & (SDL_APPINPUTFOCUS | SDL_APPACTIVE))
+		  && (!event.active.gain))
+		{
+		  /* Window has lost focus, pause the emulator.
+		   * This is similar to what PauseDOSBox() does, but the exit criteria is different.
+		   * Instead of waiting for the user to hit Alt-Break, we wait for the window to
+		   * regain window or input focus.
+		   */
+		  bool paused = true;
+		  SDL_Event ev;
+
+		  GFX_SetTitle (-1, -1, true);
+		  KEYBOARD_ClrBuffer ();
+//                                      SDL_Delay(500);
+//                                      while (SDL_PollEvent(&ev)) {
+		  // flush event queue.
+//                                      }
+
+		  while (paused)
+		    {
+		      // WaitEvent waits for an event rather than polling, so CPU usage drops to zero
+		      SDL_WaitEvent (&ev);
+
+		      switch (ev.type)
+			{
+			case SDL_QUIT:
+			  throw (0);
+			  break;	// a bit redundant at linux at least as the active events gets before the quit event.
+			case SDL_ACTIVEEVENT:	// wait until we get window focus back
+			  if (ev.active.
+			      state & (SDL_APPINPUTFOCUS | SDL_APPACTIVE))
+			    {
+			      // We've got focus back, so unpause and break out of the loop
+			      if (ev.active.gain)
+				{
+				  paused = false;
+				  GFX_SetTitle (-1, -1, false);
 				}
-			}
 
-			/* Non-focus priority is set to pause; check to see if we've lost window or input focus
-			 * i.e. has the window been minimised or made inactive?
-			 */
-			if (sdl.priority.nofocus == PRIORITY_LEVEL_PAUSE) {
-				if ((event.active.state & (SDL_APPINPUTFOCUS | SDL_APPACTIVE)) && (!event.active.gain)) {
-					/* Window has lost focus, pause the emulator.
-					 * This is similar to what PauseDOSBox() does, but the exit criteria is different.
-					 * Instead of waiting for the user to hit Alt-Break, we wait for the window to
-					 * regain window or input focus.
-					 */
-					bool paused = true;
-					SDL_Event ev;
-
-					GFX_SetTitle(-1,-1,true);
-					KEYBOARD_ClrBuffer();
-//					SDL_Delay(500);
-//					while (SDL_PollEvent(&ev)) {
-						// flush event queue.
-//					}
-
-					while (paused) {
-						// WaitEvent waits for an event rather than polling, so CPU usage drops to zero
-						SDL_WaitEvent(&ev);
-
-						switch (ev.type) {
-						case SDL_QUIT: throw(0); break; // a bit redundant at linux at least as the active events gets before the quit event.
-						case SDL_ACTIVEEVENT:     // wait until we get window focus back
-							if (ev.active.state & (SDL_APPINPUTFOCUS | SDL_APPACTIVE)) {
-								// We've got focus back, so unpause and break out of the loop
-								if (ev.active.gain) {
-									paused = false;
-									GFX_SetTitle(-1,-1,false);
-								}
-
-								/* Now poke a "release ALT" command into the keyboard buffer
-								 * we have to do this, otherwise ALT will 'stick' and cause
-								 * problems with the app running in the DOSBox.
-								 */
-								KEYBOARD_AddKey(KBD_leftalt, false);
-								KEYBOARD_AddKey(KBD_rightalt, false);
-							}
-							break;
-						}
-					}
-				}
-			}
-			break;
-		case SDL_MOUSEMOTION:
-			HandleMouseMotion(&event.motion);
-			break;
-		case SDL_MOUSEBUTTONDOWN:
-		case SDL_MOUSEBUTTONUP:
-			HandleMouseButton(&event.button);
-			break;
-		case SDL_VIDEORESIZE:
-//			HandleVideoResize(&event.resize);
-			break;
-		case SDL_QUIT:
-			throw(0);
-			break;
-		case SDL_VIDEOEXPOSE:
-			if (sdl.draw.callback) sdl.draw.callback( GFX_CallBackRedraw );
-			break;
+			      /* Now poke a "release ALT" command into the keyboard buffer
+			       * we have to do this, otherwise ALT will 'stick' and cause
+			       * problems with the app running in the DOSBox.
+			       */
+			      KEYBOARD_AddKey (KBD_leftalt, false);
+			      KEYBOARD_AddKey (KBD_rightalt, false);
+			    }
+			  break;
+			}
+		    }
+		}
+	    }
+	  break;
+	case SDL_MOUSEMOTION:
+	  HandleMouseMotion (&event.motion); // GP2X?
+	  break;
+	case SDL_MOUSEBUTTONDOWN:
+	case SDL_MOUSEBUTTONUP:
+	  HandleMouseButton (&event.button);
+	  break;
+	case SDL_VIDEORESIZE:
+//                      HandleVideoResize(&event.resize);
+	  break;
+	case SDL_QUIT:
+	  throw (0);
+	  break;
+	case SDL_VIDEOEXPOSE:
+	  if (sdl.draw.callback)
+	    sdl.draw.callback (GFX_CallBackRedraw);
+	  break;
 #ifdef WIN32
-		case SDL_KEYDOWN:
-		case SDL_KEYUP:
-			// ignore event alt+tab
-			if (event.key.keysym.sym==SDLK_LALT) sdl.laltstate = event.key.type;
-			if (event.key.keysym.sym==SDLK_RALT) sdl.raltstate = event.key.type;
-			if (((event.key.keysym.sym==SDLK_TAB)) &&
-				((sdl.laltstate==SDL_KEYDOWN) || (sdl.raltstate==SDL_KEYDOWN))) break;
-#endif
-		default:
-			void MAPPER_CheckEvent(SDL_Event * event);
-			MAPPER_CheckEvent(&event);
-		}
+	case SDL_KEYDOWN:
+	case SDL_KEYUP:
+	  // ignore event alt+tab
+	  if (event.key.keysym.sym == SDLK_LALT)
+	    sdl.laltstate = event.key.type;
+	  if (event.key.keysym.sym == SDLK_RALT)
+	    sdl.raltstate = event.key.type;
+	  if (((event.key.keysym.sym == SDLK_TAB)) &&
+	      ((sdl.laltstate == SDL_KEYDOWN)
+	       || (sdl.raltstate == SDL_KEYDOWN)))
+	    break;
+#endif
+
+		// GP2X Keyboard/Button Hack BEGIN
+		//we're going to do a real ugly hack for the GP2X here...
+		//we get the button events for 19 buttons on stick 0
+		//so we're going to turn them into key events
+		case SDL_JOYBUTTONDOWN:
+		case SDL_JOYBUTTONUP:
+            button_state = (event.type == SDL_JOYBUTTONDOWN) ? true : false;
+
+            if( gp2x_osd_virtkey == true )
+            {
+                gp2x_virtkey_press = GP2X_VirtualKeyboard( &event );
+            }
+            else
+            {
+                GP2X_ButtonPressed[event.jbutton.button] = button_state;
+            }
+
+            if( gp2x_osd_virtkey == false || (gp2x_osd_virtkey == true &&
+                                              GP2X_ButtonPressed[event.jbutton.button] == true &&
+                                              event.type == SDL_JOYBUTTONUP) )
+            {
+                if(gp2x_osd_virtkey == true) GP2X_ButtonPressed[event.jbutton.button] = false;
+
+                // Stick/DPAD mouse emulation
+                if( GP2X_MOUSE_SPEED >= 0 )
+                {
+                    switch(event.jbutton.button)
+                    {
+                        case BTN_UP:
+                            blnStickUp = button_state;
+                            break;
+                        case BTN_DOWN:
+                            blnStickDown = button_state;
+                            break;
+                        case BTN_LEFT:
+                            blnStickLeft = button_state;
+                            break;
+                        case BTN_RIGHT:
+                            blnStickRight = button_state;
+                            break;
+                        case BTN_UP_LEFT:
+                            blnStickUpLeft = button_state;
+                            break;
+                        case BTN_UP_RIGHT:
+                            blnStickUpRight = button_state;
+                            break;
+                        case BTN_DOWN_LEFT:
+                            blnStickDownLeft = button_state;
+                            break;
+                        case BTN_DOWN_RIGHT:
+                            blnStickDownRight = button_state;
+                            break;
+                    }
+                }
+
+                int tmp_button = event.jbutton.button;
+
+                if( gp2x_mouse == false || GP2X_MOUSE_SPEED < 0 || (gp2x_mouse == true && GP2X_MOUSE_SPEED >= 0 && tmp_button < 11) )
+                {
+                    if (event.type == SDL_JOYBUTTONDOWN)
+                    {
+                        event.type = SDL_KEYDOWN;
+                        event.key.state = SDL_PRESSED;
+                    }
+                    else
+                    {
+                        event.type = SDL_KEYUP;
+                        event.key.state = SDL_RELEASED;
+                    }
+
+                    event.key.keysym.scancode   = 0; // hope no one looks
+                    event.key.keysym.sym        = (SDLKey)(SDLK_KP0 + tmp_button); // SDLK_KP0 = 256
+                    event.key.keysym.mod        = KMOD_NONE;
+                    event.key.keysym.unicode    = 0; // again, hope nobody looks
+                    //printf("key: %d %d \n", tmp_button, event.key.keysym.sym);
+                }
+            }
+            else
+            {
+                if( !gp2x_virtkey_press ) break;
+            }
+            // dont break and fall through to...
+            // GP2X Keyboard/Button Hack END
+
+	default:
+	  void MAPPER_CheckEvent (SDL_Event * event);
+	  MAPPER_CheckEvent (&event);
 	}
+    }
+
+// GP2X  
+    if( GP2X_MOUSE_SPEED >= 0 && gp2x_mouse == true ) // If the parameter is > 0 then it is turned on (default = -1)
+    {
+        gp2x_mouse_speed++;
+
+        if( gp2x_mouse_speed >= GP2X_MOUSE_SPEED )
+        {
+            gp2x_mouse_speed = 0;
+
+            int x_rel = 0, y_rel = 0;
+            if( blnStickLeft  || blnStickDownLeft  || blnStickUpLeft   ) x_rel -= gp2x_mouse_pixel;
+            if( blnStickRight || blnStickDownRight || blnStickUpRight  ) x_rel += gp2x_mouse_pixel;
+            if( blnStickUp    || blnStickUpRight   || blnStickUpLeft   ) y_rel -= gp2x_mouse_pixel;
+            if( blnStickDown  || blnStickDownRight || blnStickDownLeft ) y_rel += gp2x_mouse_pixel;
+            if( x_rel != 0 || y_rel != 0 )
+            {
+                Mouse_CursorMoved( x_rel, y_rel, 1.0, 1.0, true );
+            }
+        }
+    }
+// \GP2X
+
 }
 
 #if defined (WIN32)
-static BOOL WINAPI ConsoleEventHandler(DWORD event) {
-	switch (event) {
-	case CTRL_SHUTDOWN_EVENT:
-	case CTRL_LOGOFF_EVENT:
-	case CTRL_CLOSE_EVENT:
-	case CTRL_BREAK_EVENT:
-		raise(SIGTERM);
-		return TRUE;
-	case CTRL_C_EVENT:
-	default: //pass to the next handler
-		return FALSE;
-	}
+static BOOL WINAPI
+ConsoleEventHandler (DWORD event)
+{
+  switch (event)
+    {
+    case CTRL_SHUTDOWN_EVENT:
+    case CTRL_LOGOFF_EVENT:
+    case CTRL_CLOSE_EVENT:
+    case CTRL_BREAK_EVENT:
+      raise (SIGTERM);
+      return TRUE;
+    case CTRL_C_EVENT:
+    default:			//pass to the next handler
+      return FALSE;
+    }
 }
 #endif
 
@@ -1445,462 +2989,626 @@
 /* static variable to show wether there is not a valid stdout.
  * Fixes some bugs when -noconsole is used in a read only directory */
 static bool no_stdout = false;
-void GFX_ShowMsg(char const* format,...) {
-	char buf[512];
-	va_list msg;
-	va_start(msg,format);
-	vsprintf(buf,format,msg);
-        strcat(buf,"\n");
-	va_end(msg);
-	if(!no_stdout) printf("%s",buf); //Else buf is parsed again.
+void
+GFX_ShowMsg (char const *format, ...)
+{
+  char buf[512];
+  va_list msg;
+  va_start (msg, format);
+  vsprintf (buf, format, msg);
+  strcat (buf, "\n");
+  va_end (msg);
+  if (!no_stdout)
+    printf ("%s", buf);		//Else buf is parsed again.
 }
 
 
-void Config_Add_SDL() {
-	Section_prop * sdl_sec=control->AddSection_prop("sdl",&GUI_StartUp);
-	sdl_sec->AddInitFunction(&MAPPER_StartUp);
-	Prop_bool* Pbool;
-	Prop_string* Pstring;
-	Prop_int* Pint;
-	Prop_multival* Pmulti;
-
-	Pbool = sdl_sec->Add_bool("fullscreen",Property::Changeable::Always,false);
-	Pbool->Set_help("Start dosbox directly in fullscreen. (Press ALT-Enter to go back)");
-     
-	Pbool = sdl_sec->Add_bool("fulldouble",Property::Changeable::Always,false);
-	Pbool->Set_help("Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.");
-
-	Pstring = sdl_sec->Add_string("fullresolution",Property::Changeable::Always,"original");
-	Pstring->Set_help("What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).\n"
-	                  "  Using your monitor's native resolution with aspect=true might give the best results.\n"
-			  "  If you end up with small window on a large screen, try an output different from surface.");
-
-	Pstring = sdl_sec->Add_string("windowresolution",Property::Changeable::Always,"original");
-	Pstring->Set_help("Scale the window to this size IF the output device supports hardware scaling.\n"
-	                  "  (output=surface does not!)");
+void
+Config_Add_SDL ()
+{
+  Section_prop *sdl_sec = control->AddSection_prop ("sdl", &GUI_StartUp);
+  sdl_sec->AddInitFunction (&MAPPER_StartUp);
+  Prop_bool *Pbool;
+  Prop_string *Pstring;
+  Prop_int *Pint;
+  Prop_multival *Pmulti;
+
+// these need dressing up? here ok?
+  sdl_sec->Add_int("gp2x_mouse_speed",Property::Changeable::Always, -1);   // Add use stick as mouse position (GP2X)
+  sdl_sec->Add_int("fontcolor_front",Property::Changeable::Always, 0);       // Add option to change default color of vk (GP2X)
+  sdl_sec->Add_int("fontcolor_back",Property::Changeable::Always, 15);   // Add option to change default backgnd color of vk (GP2X)
+  sdl_sec->Add_int("fontcolor_frontsel",Property::Changeable::Always, 1);       // Add option to change default color of vk (GP2X)
+  sdl_sec->Add_int("fontcolor_backsel",Property::Changeable::Always, 5);   // Add option to change default backgnd color of vk (GP2X)
+
+  Pbool =
+    sdl_sec->Add_bool ("fullscreen", Property::Changeable::Always, false);
+  Pbool->
+    Set_help
+    ("Start dosbox directly in fullscreen. (Press ALT-Enter to go back)");
+
+  Pbool =
+    sdl_sec->Add_bool ("fulldouble", Property::Changeable::Always, false);
+  Pbool->
+    Set_help
+    ("Use double buffering in fullscreen. It can reduce screen flickering, but it can also result in a slow DOSBox.");
+
+  Pstring =
+    sdl_sec->Add_string ("fullresolution", Property::Changeable::Always,
+			 "320x240"); // ("original") Caanoo
+  Pstring->
+    Set_help
+    ("What resolution to use for fullscreen: original or fixed size (e.g. 1024x768).\n"
+     "  Using your monitor's native resolution with aspect=true might give the best results.\n"
+     "  If you end up with small window on a large screen, try an output different from surface.");
+
+  Pstring =
+    sdl_sec->Add_string ("windowresolution", Property::Changeable::Always,
+			 "320x240"); //  ("original") Caanoo 
+  Pstring->
+    Set_help
+    ("Scale the window to this size IF the output device supports hardware scaling.\n"
+     "  (output=surface does not!)");
 
-	const char* outputs[] = {
-		"surface", "overlay",
+  const char *outputs[] = {
+    /* "surface", not for Caanoo */  "overlay",
 #if C_OPENGL
-		"opengl", "openglnb",
+    "opengl", "openglnb",
 #endif
 #if (HAVE_DDRAW_H) && defined(WIN32)
-		"ddraw",
+    "ddraw",
 #endif
-		0 };
-	Pstring = sdl_sec->Add_string("output",Property::Changeable::Always,"surface");
-	Pstring->Set_help("What video system to use for output.");
-	Pstring->Set_values(outputs);
-
-	Pbool = sdl_sec->Add_bool("autolock",Property::Changeable::Always,true);
-	Pbool->Set_help("Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)");
-
-	Pint = sdl_sec->Add_int("sensitivity",Property::Changeable::Always,100);
-	Pint->SetMinMax(1,1000);
-	Pint->Set_help("Mouse sensitivity.");
-
-	Pbool = sdl_sec->Add_bool("waitonerror",Property::Changeable::Always, true);
-	Pbool->Set_help("Wait before closing the console if dosbox has an error.");
-
-	Pmulti = sdl_sec->Add_multi("priority", Property::Changeable::Always, ",");
-	Pmulti->SetValue("higher,normal");
-	Pmulti->Set_help("Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.\n"
-	                 "  pause is only valid for the second entry.");
-
-	const char* actt[] = { "lowest", "lower", "normal", "higher", "highest", "pause", 0};
-	Pstring = Pmulti->GetSection()->Add_string("active",Property::Changeable::Always,"higher");
-	Pstring->Set_values(actt);
-
-	const char* inactt[] = { "lowest", "lower", "normal", "higher", "highest", "pause", 0};
-	Pstring = Pmulti->GetSection()->Add_string("inactive",Property::Changeable::Always,"normal");
-	Pstring->Set_values(inactt);
-
-	Pstring = sdl_sec->Add_path("mapperfile",Property::Changeable::Always,MAPPERFILE);
-	Pstring->Set_help("File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.");
-
-	Pbool = sdl_sec->Add_bool("usescancodes",Property::Changeable::Always,true);
-	Pbool->Set_help("Avoid usage of symkeys, might not work on all operating systems.");
-}
-
-static void show_warning(char const * const message) {
-	bool textonly = true;
+    0
+  };
+//  Pstring =
+//    sdl_sec->Add_string ("output", Property::Changeable::Always, "surface"); 
+  Pstring =
+    sdl_sec->Add_string ("output", Property::Changeable::Always, "overlay"); // CAANOO
+  Pstring->Set_help ("What video system to use for output.");
+  Pstring->Set_values (outputs);
+
+  Pbool = sdl_sec->Add_bool ("autolock", Property::Changeable::Always, true);
+  Pbool->
+    Set_help
+    ("Mouse will automatically lock, if you click on the screen. (Press CTRL-F10 to unlock)");
+
+  Pint = sdl_sec->Add_int ("sensitivity", Property::Changeable::Always, 100);
+  Pint->SetMinMax (1, 1000);
+  Pint->Set_help ("Mouse sensitivity.");
+
+  Pbool =
+    sdl_sec->Add_bool ("waitonerror", Property::Changeable::Always, true);
+  Pbool->Set_help ("Wait before closing the console if dosbox has an error.");
+
+  Pmulti = sdl_sec->Add_multi ("priority", Property::Changeable::Always, ",");
+  Pmulti->SetValue ("higher,normal");
+  Pmulti->
+    Set_help
+    ("Priority levels for dosbox. Second entry behind the comma is for when dosbox is not focused/minimized.\n"
+     "  pause is only valid for the second entry.");
+
+  const char *actt[] =
+    { "lowest", "lower", "normal", "higher", "highest", "pause", 0 };
+  Pstring =
+    Pmulti->GetSection ()->Add_string ("active", Property::Changeable::Always,
+				       "higher");
+  Pstring->Set_values (actt);
+
+  const char *inactt[] =
+    { "lowest", "lower", "normal", "higher", "highest", "pause", 0 };
+  Pstring =
+    Pmulti->GetSection ()->Add_string ("inactive",
+				       Property::Changeable::Always,
+				       "normal");
+  Pstring->Set_values (inactt);
+
+  Pstring =
+    sdl_sec->Add_path ("mapperfile", Property::Changeable::Always,
+		       MAPPERFILE);
+  Pstring->
+    Set_help
+    ("File used to load/save the key/event mappings from. Resetmapper only works with the defaul value.");
+
+  Pbool =
+    sdl_sec->Add_bool ("usescancodes", Property::Changeable::Always, true);
+  Pbool->
+    Set_help
+    ("Avoid usage of symkeys, might not work on all operating systems.");
+}
+
+static void
+show_warning (char const *const message)
+{
+  bool textonly = true;
 #ifdef WIN32
-	textonly = false;
-	if ( !sdl.inited && SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) < 0 ) textonly = true;
-	sdl.inited = true;
-#endif
-	printf(message);
-	if(textonly) return;
-	if(!sdl.surface) sdl.surface = SDL_SetVideoMode(640,400,0,0);
-	if(!sdl.surface) return;
+  textonly = false;
+  if (!sdl.inited && SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0)
+    textonly = true;
+  sdl.inited = true;
+#endif
+  printf (message);
+  if (textonly)
+    return;
+  if (!sdl.surface)
+    sdl.surface = SDL_SetVideoMode (640, 400, 0, 0);
+  if (!sdl.surface)
+    return;
 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
-	Bit32u rmask = 0xff000000;
-	Bit32u gmask = 0x00ff0000;
-	Bit32u bmask = 0x0000ff00;
+  Bit32u rmask = 0xff000000;
+  Bit32u gmask = 0x00ff0000;
+  Bit32u bmask = 0x0000ff00;
 #else
-	Bit32u rmask = 0x000000ff;
-	Bit32u gmask = 0x0000ff00;                    
-	Bit32u bmask = 0x00ff0000;
-#endif
-	SDL_Surface* splash_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, 640, 400, 32, rmask, gmask, bmask, 0);
-	if (!splash_surf) return;
-
-	int x = 120,y = 20;
-	std::string m(message),m2;
-	std::string::size_type a,b,c,d;
-   
-	while(m.size()) { //Max 50 characters. break on space before or on a newline
-		c = m.find('\n');
-		d = m.rfind(' ',50);
-		if(c>d) a=b=d; else a=b=c;
-		if( a != std::string::npos) b++; 
-		m2 = m.substr(0,a); m.erase(0,b);
-		OutputString(x,y,m2.c_str(),0xffffffff,0,splash_surf);
-		y += 20;
-	}
-   
-	SDL_BlitSurface(splash_surf, NULL, sdl.surface, NULL);
-	SDL_Flip(sdl.surface);
-	SDL_Delay(12000);
-}
-   
-static void launcheditor() {
-	std::string path,file;
-	Cross::CreatePlatformConfigDir(path);
-	Cross::GetPlatformConfigName(file);
-	path += file;
-	FILE* f = fopen(path.c_str(),"r");
-	if(!f && !control->PrintConfig(path.c_str())) {
-		printf("tried creating %s. but failed.\n",path.c_str());
-		exit(1);
-	}
-	if(f) fclose(f);
+  Bit32u rmask = 0x000000ff;
+  Bit32u gmask = 0x0000ff00;
+  Bit32u bmask = 0x00ff0000;
+#endif
+  SDL_Surface *splash_surf =
+    SDL_CreateRGBSurface (SDL_SWSURFACE, 640, 400, 32, rmask, gmask, bmask,
+			  0);
+  if (!splash_surf)
+    return;
+
+  int x = 120, y = 20;
+  std::string m (message), m2;
+  std::string::size_type a, b, c, d;
+
+  while (m.size ())
+    {				//Max 50 characters. break on space before or on a newline
+      c = m.find ('\n');
+      d = m.rfind (' ', 50);
+      if (c > d)
+	a = b = d;
+      else
+	a = b = c;
+      if (a != std::string::npos)
+	b++;
+      m2 = m.substr (0, a);
+      m.erase (0, b);
+      OutputString (x, y, m2.c_str (), 0xffffffff, 0, splash_surf);
+      y += 20;
+    }
+
+  SDL_BlitSurface (splash_surf, NULL, sdl.surface, NULL);
+  SDL_Flip (sdl.surface);
+  SDL_Delay (12000);
+}
+
+static void
+launcheditor ()
+{
+  std::string path, file;
+  Cross::CreatePlatformConfigDir (path);
+  Cross::GetPlatformConfigName (file);
+  path += file;
+  FILE *f = fopen (path.c_str (), "r");
+  if (!f && !control->PrintConfig (path.c_str ()))
+    {
+      printf ("tried creating %s. but failed.\n", path.c_str ());
+      exit (1);
+    }
+  if (f)
+    fclose (f);
 /*	if(edit.empty()) {
 		printf("no editor specified.\n");
 		exit(1);
 	}*/
-	std::string edit;
-	while(control->cmdline->FindString("-editconf",edit,true)) //Loop until one succeeds
-		execlp(edit.c_str(),edit.c_str(),path.c_str(),(char*) 0);
-	//if you get here the launching failed!
-	printf("can't find editor(s) specified at the command line.\n");
-	exit(1);
-}
-static void launchcaptures(std::string const& edit) {
-	std::string path,file;
-	Section* t = control->GetSection("dosbox");
-	if(t) file = t->GetPropValue("captures");
-	if(!t || file == NO_SUCH_PROPERTY) {
-		printf("Config system messed up.\n");
-		exit(1);
-	}
-	Cross::CreatePlatformConfigDir(path);
-	path += file;
-	Cross::CreateDir(path);
-	struct stat cstat;
-	if(stat(path.c_str(),&cstat) || (cstat.st_mode & S_IFDIR) == 0) {
-		printf("%s doesn't exists or isn't a directory.\n",path.c_str());
-		exit(1);
-	}
+  std::string edit;
+  while (control->cmdline->FindString ("-editconf", edit, true))	//Loop until one succeeds
+    execlp (edit.c_str (), edit.c_str (), path.c_str (), (char *) 0);
+  //if you get here the launching failed!
+  printf ("can't find editor(s) specified at the command line.\n");
+  exit (1);
+}
+
+static void
+launchcaptures (std::string const &edit)
+{
+  std::string path, file;
+  Section *t = control->GetSection ("dosbox");
+  if (t)
+    file = t->GetPropValue ("captures");
+  if (!t || file == NO_SUCH_PROPERTY)
+    {
+      printf ("Config system messed up.\n");
+      exit (1);
+    }
+  Cross::CreatePlatformConfigDir (path);
+  path += file;
+  Cross::CreateDir (path);
+  struct stat cstat;
+  if (stat (path.c_str (), &cstat) || (cstat.st_mode & S_IFDIR) == 0)
+    {
+      printf ("%s doesn't exists or isn't a directory.\n", path.c_str ());
+      exit (1);
+    }
 /*	if(edit.empty()) {
 		printf("no editor specified.\n");
 		exit(1);
 	}*/
 
-	execlp(edit.c_str(),edit.c_str(),path.c_str(),(char*) 0);
-	//if you get here the launching failed!
-	printf("can't find filemanager %s\n",edit.c_str());
-	exit(1);
-}
-
-static void printconfiglocation() {
-	std::string path,file;
-	Cross::CreatePlatformConfigDir(path);
-	Cross::GetPlatformConfigName(file);
-	path += file;
-     
-	FILE* f = fopen(path.c_str(),"r");
-	if(!f && !control->PrintConfig(path.c_str())) {
-		printf("tried creating %s. but failed",path.c_str());
-		exit(1);
-	}
-	if(f) fclose(f);
-	printf("%s\n",path.c_str());
-	exit(0);
-}
-
-static void eraseconfigfile() {
-	FILE* f = fopen("dosbox.conf","r");
-	if(f) {
-		fclose(f);
-		show_warning("Warning: dosbox.conf exists in current working directory.\nThis will override the configuration file at runtime.\n");
-	}
-	std::string path,file;
-	Cross::GetPlatformConfigDir(path);
-	Cross::GetPlatformConfigName(file);
-	path += file;
-	f = fopen(path.c_str(),"r");
-	if(!f) exit(0);
-	fclose(f);
-	unlink(path.c_str());
-	exit(0);
-}
-
-static void erasemapperfile() {
-	FILE* g = fopen("dosbox.conf","r");
-	if(g) {
-		fclose(g);
-		show_warning("Warning: dosbox.conf exists in current working directory.\nKeymapping might not be properly reset.\n"
-		             "Please reset configuration as well and delete the dosbox.conf.\n");
-	}
-
-	std::string path,file=MAPPERFILE;
-	Cross::GetPlatformConfigDir(path);
-	path += file;
-	FILE* f = fopen(path.c_str(),"r");
-	if(!f) exit(0);
-	fclose(f);
-	unlink(path.c_str());
-	exit(0);
+  execlp (edit.c_str (), edit.c_str (), path.c_str (), (char *) 0);
+  //if you get here the launching failed!
+  printf ("can't find filemanager %s\n", edit.c_str ());
+  exit (1);
+}
+
+static void
+printconfiglocation ()
+{
+  std::string path, file;
+  Cross::CreatePlatformConfigDir (path);
+  Cross::GetPlatformConfigName (file);
+  path += file;
+
+  FILE *f = fopen (path.c_str (), "r");
+  if (!f && !control->PrintConfig (path.c_str ()))
+    {
+      printf ("tried creating %s. but failed", path.c_str ());
+      exit (1);
+    }
+  if (f)
+    fclose (f);
+  printf ("%s\n", path.c_str ());
+  exit (0);
+}
+
+static void
+eraseconfigfile ()
+{
+  FILE *f = fopen ("dosbox.conf", "r");
+  if (f)
+    {
+      fclose (f);
+      show_warning
+	("Warning: dosbox.conf exists in current working directory.\nThis will override the configuration file at runtime.\n");
+    }
+  std::string path, file;
+  Cross::GetPlatformConfigDir (path);
+  Cross::GetPlatformConfigName (file);
+  path += file;
+  f = fopen (path.c_str (), "r");
+  if (!f)
+    exit (0);
+  fclose (f);
+  unlink (path.c_str ());
+  exit (0);
+}
+
+static void
+erasemapperfile ()
+{
+  FILE *g = fopen ("dosbox.conf", "r");
+  if (g)
+    {
+      fclose (g);
+      show_warning
+	("Warning: dosbox.conf exists in current working directory.\nKeymapping might not be properly reset.\n"
+	 "Please reset configuration as well and delete the dosbox.conf.\n");
+    }
+
+  std::string path, file = MAPPERFILE;
+  Cross::GetPlatformConfigDir (path);
+  path += file;
+  FILE *f = fopen (path.c_str (), "r");
+  if (!f)
+    exit (0);
+  fclose (f);
+  unlink (path.c_str ());
+  exit (0);
 }
 
 
 
 //extern void UI_Init(void);
-int main(int argc, char* argv[]) {
-	try {
-		CommandLine com_line(argc,argv);
-		Config myconf(&com_line);
-		control=&myconf;
-		/* Init the configuration system and add default values */
-		Config_Add_SDL();
-		DOSBOX_Init();
-
-		std::string editor;
-		if(control->cmdline->FindString("-editconf",editor,false)) launcheditor();
-		if(control->cmdline->FindString("-opencaptures",editor,true)) launchcaptures(editor);
-		if(control->cmdline->FindExist("-eraseconf")) eraseconfigfile();
-		if(control->cmdline->FindExist("-resetconf")) eraseconfigfile();
-		if(control->cmdline->FindExist("-erasemapper")) erasemapperfile();
-		if(control->cmdline->FindExist("-resetmapper")) erasemapperfile();
+int
+main (int argc, char *argv[])
+{
+  try
+  {
+    CommandLine com_line (argc, argv);
+    Config myconf (&com_line);
+    control = &myconf;
+    /* Init the configuration system and add default values */
+    Config_Add_SDL ();
+    DOSBOX_Init ();
+
+    std::string editor;
+    if (control->cmdline->FindString ("-editconf", editor, false))
+      launcheditor ();
+    if (control->cmdline->FindString ("-opencaptures", editor, true))
+      launchcaptures (editor);
+    if (control->cmdline->FindExist ("-eraseconf"))
+      eraseconfigfile ();
+    if (control->cmdline->FindExist ("-resetconf"))
+      eraseconfigfile ();
+    if (control->cmdline->FindExist ("-erasemapper"))
+      erasemapperfile ();
+    if (control->cmdline->FindExist ("-resetmapper"))
+      erasemapperfile ();
 
-		/* Can't disable the console with debugger enabled */
+    /* Can't disable the console with debugger enabled */
 #if defined(WIN32) && !(C_DEBUG)
-		if (control->cmdline->FindExist("-noconsole")) {
-			FreeConsole();
-			/* Redirect standard input and standard output */
-			if(freopen(STDOUT_FILE, "w", stdout) == NULL)
-				no_stdout = true; // No stdout so don't write messages
-			freopen(STDERR_FILE, "w", stderr);
-			setvbuf(stdout, NULL, _IOLBF, BUFSIZ);	/* Line buffered */
-			setbuf(stderr, NULL);					/* No buffering */
-		} else {
-			if (AllocConsole()) {
-				fclose(stdin);
-				fclose(stdout);
-				fclose(stderr);
-				freopen("CONIN$","r",stdin);
-				freopen("CONOUT$","w",stdout);
-				freopen("CONOUT$","w",stderr);
-			}
-			SetConsoleTitle("DOSBox Status Window");
-		}
-#endif  //defined(WIN32) && !(C_DEBUG)
-		if (control->cmdline->FindExist("-version") ||
-		    control->cmdline->FindExist("--version") ) {
-			printf("\nDOSBox version %s, copyright 2002-2010 DOSBox Team.\n\n",VERSION);
-			printf("DOSBox is written by the DOSBox Team (See AUTHORS file))\n");
-			printf("DOSBox comes with ABSOLUTELY NO WARRANTY.  This is free software,\n");
-			printf("and you are welcome to redistribute it under certain conditions;\n");
-			printf("please read the COPYING file thoroughly before doing so.\n\n");
-			return 0;
-		}
-		if(control->cmdline->FindExist("-printconf")) printconfiglocation();
+    if (control->cmdline->FindExist ("-noconsole"))
+      {
+	FreeConsole ();
+	/* Redirect standard input and standard output */
+	if (freopen (STDOUT_FILE, "w", stdout) == NULL)
+	  no_stdout = true;	// No stdout so don't write messages
+	freopen (STDERR_FILE, "w", stderr);
+	setvbuf (stdout, NULL, _IOLBF, BUFSIZ);	/* Line buffered */
+	setbuf (stderr, NULL);	/* No buffering */
+      }
+    else
+      {
+	if (AllocConsole ())
+	  {
+	    fclose (stdin);
+	    fclose (stdout);
+	    fclose (stderr);
+	    freopen ("CONIN$", "r", stdin);
+	    freopen ("CONOUT$", "w", stdout);
+	    freopen ("CONOUT$", "w", stderr);
+	  }
+	SetConsoleTitle ("DOSBox Status Window");
+      }
+#endif //defined(WIN32) && !(C_DEBUG)
+    if (control->cmdline->FindExist ("-version") ||
+	control->cmdline->FindExist ("--version"))
+      {
+	printf ("\nDOSBox version %s, copyright 2002-2010 DOSBox Team.\n\n",
+		VERSION);
+	printf ("DOSBox is written by the DOSBox Team (See AUTHORS file))\n");
+	printf
+	  ("DOSBox comes with ABSOLUTELY NO WARRANTY.  This is free software,\n");
+	printf
+	  ("and you are welcome to redistribute it under certain conditions;\n");
+	printf
+	  ("please read the COPYING file thoroughly before doing so.\n\n");
+	return 0;
+      }
+    if (control->cmdline->FindExist ("-printconf"))
+      printconfiglocation ();
 
 #if C_DEBUG
-		DEBUG_SetupConsole();
+    DEBUG_SetupConsole ();
 #endif
 
 #if defined(WIN32)
-	SetConsoleCtrlHandler((PHANDLER_ROUTINE) ConsoleEventHandler,TRUE);
+    SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ConsoleEventHandler, TRUE);
 #endif
 
 #ifdef OS2
-        PPIB pib;
-        PTIB tib;
-        DosGetInfoBlocks(&tib, &pib);
-        if (pib->pib_ultype == 2) pib->pib_ultype = 3;
-        setbuf(stdout, NULL);
-        setbuf(stderr, NULL);
+    PPIB pib;
+    PTIB tib;
+    DosGetInfoBlocks (&tib, &pib);
+    if (pib->pib_ultype == 2)
+      pib->pib_ultype = 3;
+    setbuf (stdout, NULL);
+    setbuf (stderr, NULL);
 #endif
 
-	/* Display Welcometext in the console */
-	LOG_MSG("DOSBox version %s",VERSION);
-	LOG_MSG("Copyright 2002-2010 DOSBox Team, published under GNU GPL.");
-	LOG_MSG("---");
+    /* Display Welcometext in the console */
+    LOG_MSG ("DOSBox version %s", VERSION);
+    LOG_MSG ("Copyright 2002-2010 DOSBox Team, published under GNU GPL.");
+    LOG_MSG ("---");
 
-	/* Init SDL */
+    /* Init SDL */
 #if SDL_VERSION_ATLEAST(1, 2, 14)
-	putenv(const_cast<char*>("SDL_DISABLE_LOCK_KEYS=1"));
+    putenv (const_cast < char *>("SDL_DISABLE_LOCK_KEYS=1"));
 #endif
-	if ( SDL_Init( SDL_INIT_AUDIO|SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_CDROM
-		|SDL_INIT_NOPARACHUTE
-		) < 0 ) E_Exit("Can't init SDL %s",SDL_GetError());
-	sdl.inited = true;
+    if (SDL_Init
+	(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_CDROM |
+	 SDL_INIT_NOPARACHUTE) < 0)
+      E_Exit ("Can't init SDL %s", SDL_GetError ());
+    sdl.inited = true;
 
 #ifndef DISABLE_JOYSTICK
-	//Initialise Joystick seperately. This way we can warn when it fails instead
-	//of exiting the application
-	if( SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0 ) LOG_MSG("Failed to init joystick support");
+    //Initialise Joystick seperately. This way we can warn when it fails instead
+    //of exiting the application
+    if (SDL_InitSubSystem (SDL_INIT_JOYSTICK) < 0)
+      LOG_MSG ("Failed to init joystick support");
+  	psp_sdl_joy=SDL_JoystickOpen(0); // GP2X/CAANOO Need to force the joystick to open       
 #endif
 
-	sdl.laltstate = SDL_KEYUP;
-	sdl.raltstate = SDL_KEYUP;
+	// Init SDL_ttf for OSD (GP2X/CAANOO)
+	if ( TTF_Init() < 0 )
+		E_Exit("Can't init SDL_ttf %s",TTF_GetError());
+
+    sdl.fontsize = 14;
+    GP2X_LoadFont( sdl.fontsize );
+
+	sdl.curfps=sdl.fps=sdl.fpstime=0; // \GP2X/CAANOO
+
+
+    sdl.laltstate = SDL_KEYUP;
+    sdl.raltstate = SDL_KEYUP;
 
 #if defined (WIN32)
 #if SDL_VERSION_ATLEAST(1, 2, 10)
-		sdl.using_windib=true;
+    sdl.using_windib = true;
 #else
-		sdl.using_windib=false;
-#endif
-		char sdl_drv_name[128];
-		if (getenv("SDL_VIDEODRIVER")==NULL) {
-			if (SDL_VideoDriverName(sdl_drv_name,128)!=NULL) {
-				sdl.using_windib=false;
-				if (strcmp(sdl_drv_name,"directx")!=0) {
-					SDL_QuitSubSystem(SDL_INIT_VIDEO);
-					putenv("SDL_VIDEODRIVER=directx");
-					if (SDL_InitSubSystem(SDL_INIT_VIDEO)<0) {
-						putenv("SDL_VIDEODRIVER=windib");
-						if (SDL_InitSubSystem(SDL_INIT_VIDEO)<0) E_Exit("Can't init SDL Video %s",SDL_GetError());
-						sdl.using_windib=true;
-					}
-				}
-			}
-		} else {
-			char* sdl_videodrv = getenv("SDL_VIDEODRIVER");
-			if (strcmp(sdl_videodrv,"directx")==0) sdl.using_windib = false;
-			else if (strcmp(sdl_videodrv,"windib")==0) sdl.using_windib = true;
-		}
-		if (SDL_VideoDriverName(sdl_drv_name,128)!=NULL) {
-			if (strcmp(sdl_drv_name,"windib")==0) LOG_MSG("SDL_Init: Starting up with SDL windib video driver.\n          Try to update your video card and directx drivers!");
-		}
+    sdl.using_windib = false;
 #endif
-	sdl.num_joysticks=SDL_NumJoysticks();
-
-	/* Parse configuration files */
-	std::string config_file,config_path;
-	bool parsed_anyconfigfile = false;
-	//First Parse -userconf
-	if(control->cmdline->FindExist("-userconf",true)){
-		config_file.clear();
-		Cross::GetPlatformConfigDir(config_path);
-		Cross::GetPlatformConfigName(config_file);
-		config_path += config_file;
-		if(control->ParseConfigFile(config_path.c_str())) parsed_anyconfigfile = true;
-		if(!parsed_anyconfigfile) {
-			//Try to create the userlevel configfile.
-			config_file.clear();
-			Cross::CreatePlatformConfigDir(config_path);
-			Cross::GetPlatformConfigName(config_file);
-			config_path += config_file;
-			if(control->PrintConfig(config_path.c_str())) {
-				LOG_MSG("CONFIG: Generating default configuration.\nWriting it to %s",config_path.c_str());
-				//Load them as well. Makes relative paths much easier
-				if(control->ParseConfigFile(config_path.c_str())) parsed_anyconfigfile = true;
-			}
-		}
-	}
-
-	//Second parse -conf entries
-	while(control->cmdline->FindString("-conf",config_file,true))
-		if (control->ParseConfigFile(config_file.c_str())) parsed_anyconfigfile = true;
-
-	//if none found => parse localdir conf
-	config_file = "dosbox.conf";
-	if (!parsed_anyconfigfile && control->ParseConfigFile(config_file.c_str())) parsed_anyconfigfile = true;
-
-	//if none found => parse userlevel conf
-	if(!parsed_anyconfigfile) {
-		config_file.clear();
-		Cross::GetPlatformConfigDir(config_path);
-		Cross::GetPlatformConfigName(config_file);
-		config_path += config_file;
-		if(control->ParseConfigFile(config_path.c_str())) parsed_anyconfigfile = true;
-	}
-
-	if(!parsed_anyconfigfile) {
-		//Try to create the userlevel configfile.
-		config_file.clear();
-		Cross::CreatePlatformConfigDir(config_path);
-		Cross::GetPlatformConfigName(config_file);
-		config_path += config_file;
-		if(control->PrintConfig(config_path.c_str())) {
-			LOG_MSG("CONFIG: Generating default configuration.\nWriting it to %s",config_path.c_str());
-			//Load them as well. Makes relative paths much easier
-			control->ParseConfigFile(config_path.c_str());
-		} else {
-			LOG_MSG("CONFIG: Using default settings. Create a configfile to change them");
-		}
-	}
+    char sdl_drv_name[128];
+    if (getenv ("SDL_VIDEODRIVER") == NULL)
+      {
+	if (SDL_VideoDriverName (sdl_drv_name, 128) != NULL)
+	  {
+	    sdl.using_windib = false;
+	    if (strcmp (sdl_drv_name, "directx") != 0)
+	      {
+		SDL_QuitSubSystem (SDL_INIT_VIDEO);
+		putenv ("SDL_VIDEODRIVER=directx");
+		if (SDL_InitSubSystem (SDL_INIT_VIDEO) < 0)
+		  {
+		    putenv ("SDL_VIDEODRIVER=windib");
+		    if (SDL_InitSubSystem (SDL_INIT_VIDEO) < 0)
+		      E_Exit ("Can't init SDL Video %s", SDL_GetError ());
+		    sdl.using_windib = true;
+		  }
+	      }
+	  }
+      }
+    else
+      {
+	char *sdl_videodrv = getenv ("SDL_VIDEODRIVER");
+	if (strcmp (sdl_videodrv, "directx") == 0)
+	  sdl.using_windib = false;
+	else if (strcmp (sdl_videodrv, "windib") == 0)
+	  sdl.using_windib = true;
+      }
+    if (SDL_VideoDriverName (sdl_drv_name, 128) != NULL)
+      {
+	if (strcmp (sdl_drv_name, "windib") == 0)
+	  LOG_MSG
+	    ("SDL_Init: Starting up with SDL windib video driver.\n          Try to update your video card and directx drivers!");
+      }
+#endif
+    sdl.num_joysticks = SDL_NumJoysticks ();
+
+    /* Parse configuration files */
+    std::string config_file, config_path;
+    bool parsed_anyconfigfile = false;
+    //First Parse -userconf
+    if (control->cmdline->FindExist ("-userconf", true))
+      {
+	config_file.clear ();
+	Cross::GetPlatformConfigDir (config_path);
+	Cross::GetPlatformConfigName (config_file);
+	config_path += config_file;
+	if (control->ParseConfigFile (config_path.c_str ()))
+	  parsed_anyconfigfile = true;
+	if (!parsed_anyconfigfile)
+	  {
+	    //Try to create the userlevel configfile.
+	    config_file.clear ();
+	    Cross::CreatePlatformConfigDir (config_path);
+	    Cross::GetPlatformConfigName (config_file);
+	    config_path += config_file;
+	    if (control->PrintConfig (config_path.c_str ()))
+	      {
+		LOG_MSG
+		  ("CONFIG: Generating default configuration.\nWriting it to %s",
+		   config_path.c_str ());
+		//Load them as well. Makes relative paths much easier
+		if (control->ParseConfigFile (config_path.c_str ()))
+		  parsed_anyconfigfile = true;
+	      }
+	  }
+      }
+
+    //Second parse -conf entries
+    while (control->cmdline->FindString ("-conf", config_file, true))
+      if (control->ParseConfigFile (config_file.c_str ()))
+	parsed_anyconfigfile = true;
+
+    //if none found => parse localdir conf
+    config_file = "dosbox.conf";
+    if (!parsed_anyconfigfile
+	&& control->ParseConfigFile (config_file.c_str ()))
+      parsed_anyconfigfile = true;
+
+    //if none found => parse userlevel conf
+    if (!parsed_anyconfigfile)
+      {
+	config_file.clear ();
+	Cross::GetPlatformConfigDir (config_path);
+	Cross::GetPlatformConfigName (config_file);
+	config_path += config_file;
+	if (control->ParseConfigFile (config_path.c_str ()))
+	  parsed_anyconfigfile = true;
+      }
+
+    if (!parsed_anyconfigfile)
+      {
+	//Try to create the userlevel configfile.
+	config_file.clear ();
+	Cross::CreatePlatformConfigDir (config_path);
+	Cross::GetPlatformConfigName (config_file);
+	config_path += config_file;
+	if (control->PrintConfig (config_path.c_str ()))
+	  {
+	    LOG_MSG
+	      ("CONFIG: Generating default configuration.\nWriting it to %s",
+	       config_path.c_str ());
+	    //Load them as well. Makes relative paths much easier
+	    control->ParseConfigFile (config_path.c_str ());
+	  }
+	else
+	  {
+	    LOG_MSG
+	      ("CONFIG: Using default settings. Create a configfile to change them");
+	  }
+      }
 
 
 #if (ENVIRON_LINKED)
-		control->ParseEnv(environ);
+    control->ParseEnv (environ);
 #endif
-//		UI_Init();
-//		if (control->cmdline->FindExist("-startui")) UI_Run(false);
-		/* Init all the sections */
-		control->Init();
-		/* Some extra SDL Functions */
-		Section_prop * sdl_sec=static_cast<Section_prop *>(control->GetSection("sdl"));
-
-		if (control->cmdline->FindExist("-fullscreen") || sdl_sec->Get_bool("fullscreen")) {
-			if(!sdl.desktop.fullscreen) { //only switch if not allready in fullscreen
-				GFX_SwitchFullScreen();
-			}
-		}
-
-		/* Init the keyMapper */
-		MAPPER_Init();
-		if (control->cmdline->FindExist("-startmapper")) MAPPER_RunInternal();
-		/* Start up main machine */
-		control->StartUp();
-		/* Shutdown everything */
-	} catch (char * error) {
-		GFX_ShowMsg("Exit to error: %s",error);
-		fflush(NULL);
-		if(sdl.wait_on_error) {
-			//TODO Maybe look for some way to show message in linux?
+//              UI_Init();
+//              if (control->cmdline->FindExist("-startui")) UI_Run(false);
+    /* Init all the sections */
+    control->Init ();
+    /* Some extra SDL Functions */
+    Section_prop *sdl_sec =
+      static_cast < Section_prop * >(control->GetSection ("sdl"));
+
+    if (control->cmdline->FindExist ("-fullscreen")
+	|| sdl_sec->Get_bool ("fullscreen"))
+      {
+	if (!sdl.desktop.fullscreen)
+	  {			//only switch if not allready in fullscreen
+	    GFX_SwitchFullScreen ();
+	  }
+      }
+
+    /* Init the keyMapper */
+    MAPPER_Init ();
+    if (control->cmdline->FindExist ("-startmapper"))
+      MAPPER_RunInternal ();
+    /* Start up main machine */
+    control->StartUp ();
+    /* Shutdown everything */
+  }
+  catch (char *error)
+  {
+    GFX_ShowMsg ("Exit to error: %s", error);
+    fflush (NULL);
+    if (sdl.wait_on_error)
+      {
+	//TODO Maybe look for some way to show message in linux?
 #if (C_DEBUG)
-			GFX_ShowMsg("Press enter to continue");
-			fflush(NULL);
-			fgetc(stdin);
+	GFX_ShowMsg ("Press enter to continue");
+	fflush (NULL);
+	fgetc (stdin);
 #elif defined(WIN32)
-			Sleep(5000);
+	Sleep (5000);
 #endif
-		}
-
-	}
-	catch (int){
-		;//nothing pressed killswitch
-	}
-	catch(...){
-		//Force visible mouse to end user. Somehow this sometimes doesn't happen
-		SDL_WM_GrabInput(SDL_GRAB_OFF);
-		SDL_ShowCursor(SDL_ENABLE);
-		throw;//dunno what happened. rethrow for sdl to catch
-	}
-	//Force visible mouse to end user. Somehow this sometimes doesn't happen
-	SDL_WM_GrabInput(SDL_GRAB_OFF);
-	SDL_ShowCursor(SDL_ENABLE);
-
-	SDL_Quit();//Let's hope sdl will quit as well when it catches an exception
-	return 0;
-}
+      }
 
-void GFX_GetSize(int &width, int &height, bool &fullscreen) {
-	width = sdl.draw.width;
-	height = sdl.draw.height;
-	fullscreen = sdl.desktop.fullscreen;
+  }
+  catch (int)
+  {
+    ;				//nothing pressed killswitch
+  }
+  catch (...)
+  {
+    //Force visible mouse to end user. Somehow this sometimes doesn't happen
+    SDL_WM_GrabInput (SDL_GRAB_OFF);
+    SDL_ShowCursor (SDL_ENABLE);
+    throw;			//dunno what happened. rethrow for sdl to catch
+  }
+  //Force visible mouse to end user. Somehow this sometimes doesn't happen
+  SDL_WM_GrabInput (SDL_GRAB_OFF);
+  SDL_ShowCursor (SDL_ENABLE);
+
+  SDL_Quit ();			//Let's hope sdl will quit as well when it catches an exception
+  return 0;
+}
+
+void
+GFX_GetSize (int &width, int &height, bool & fullscreen)
+{
+  width = sdl.draw.width;
+  height = sdl.draw.height;
+  fullscreen = sdl.desktop.fullscreen;
 }
--- dosbox-0.74/src/ints/mouse.cpp	2010-05-10 19:43:54.000000000 +0200
+++ working-0.74/src/ints/mouse.cpp	2012-01-14 21:14:12.326000092 +0100
@@ -446,6 +446,15 @@
 	RestoreVgaRegisters();
 }
 
+// GP2X BEGIN - fixed mouse position hack - pct: 0.0-1.0
+void Mouse_CursorMovedFixed(float xpct,float ypct,bool emulate) {
+	float xpos=mouse.max_x*xpct, ypos=mouse.max_y*ypct;
+	//LOG_MSG("CMF: %f %f [%f %f] = %f %f (%f %f)", xpct, ypct, mouse.x, mouse.y, xpos, ypos, xpos-mouse.x, ypos-mouse.y);
+	Mouse_CursorMoved((xpos-mouse.x)/mouse.pixelPerMickey_x, (ypos-mouse.y)/mouse.pixelPerMickey_y, xpct, ypct, emulate);
+	//LOG_MSG("CMF2: %f %f", mouse.x, mouse.y);
+}
+// GP2X END
+
 void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate) {
 	float dx = xrel * mouse.pixelPerMickey_x;
 	float dy = yrel * mouse.pixelPerMickey_y;
--- dosbox-0.74/src/Makefile.am	2010-05-10 19:43:54.000000000 +0200
+++ working-0.74/src/Makefile.am	2012-01-14 21:14:12.327000092 +0100
@@ -13,8 +13,9 @@
 
 dosbox_SOURCES = dosbox.cpp $(ico_stuff)
 dosbox_LDADD = cpu/libcpu.a debug/libdebug.a dos/libdos.a fpu/libfpu.a  hardware/libhardware.a gui/libgui.a \
-               ints/libints.a misc/libmisc.a shell/libshell.a hardware/serialport/libserial.a libs/gui_tk/libgui_tk.a
-
+               ints/libints.a misc/libmisc.a shell/libshell.a hardware/serialport/libserial.a libs/gui_tk/libgui_tk.a \
+               -lSDL_ttf -lfreetype
+               
 EXTRA_DIST = winres.rc dosbox.ico
 
 
--- dosbox-0.74/src/Makefile.in	2010-05-12 11:57:43.000000000 +0200
+++ working-0.74/src/Makefile.in	2012-01-14 21:14:12.324000092 +0100
@@ -218,7 +218,8 @@
 @HAVE_WINDRES_TRUE@ico_stuff = winres.rc
 dosbox_SOURCES = dosbox.cpp $(ico_stuff)
 dosbox_LDADD = cpu/libcpu.a debug/libdebug.a dos/libdos.a fpu/libfpu.a  hardware/libhardware.a gui/libgui.a \
-               ints/libints.a misc/libmisc.a shell/libshell.a hardware/serialport/libserial.a libs/gui_tk/libgui_tk.a
+               ints/libints.a misc/libmisc.a shell/libshell.a hardware/serialport/libserial.a libs/gui_tk/libgui_tk.a \
+               -lSDL_ttf -lfreetype
 
 EXTRA_DIST = winres.rc dosbox.ico
 all: all-recursive
