More code moved to the X11 driver (bitmap and palette and misc).

diff --git a/controls/desktop.c b/controls/desktop.c
index f2573f8..50a9fd1 100644
--- a/controls/desktop.c
+++ b/controls/desktop.c
@@ -4,8 +4,6 @@
  * Copyright 1994 Alexandre Julliard
  */
 
-#include "x11drv.h"
-
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>
@@ -17,6 +15,19 @@
 #include "win.h"
 #include "wine/winuser16.h"
 
+/**********************************************************************/
+
+DESKTOP_DRIVER *DESKTOP_Driver = NULL;
+
+/***********************************************************************
+ *		DESKTOP_IsSingleWindow
+ */
+BOOL DESKTOP_IsSingleWindow()
+{
+  DESKTOP *pDesktop = (DESKTOP *) WIN_GetDesktop()->wExtra;
+  return MONITOR_IsSingleWindow(pDesktop->pPrimaryMonitor);
+}
+
 /***********************************************************************
  *              DESKTOP_GetScreenWidth
  *
@@ -206,8 +217,7 @@
         goto END;
 	
     case WM_ERASEBKGND:
-	if (X11DRV_WND_GetXRootWindow(wndPtr) == 
-	    DefaultRootWindow(display))
+	if(!DESKTOP_IsSingleWindow())
         {
             retvalue = 1;
             goto END;
diff --git a/debugger/dbg.y b/debugger/dbg.y
index 849ab84..aabfa8e 100644
--- a/debugger/dbg.y
+++ b/debugger/dbg.y
@@ -6,16 +6,13 @@
  * Copyright 1995 Morten Welinder
  */
 
-#include "config.h"
-#include "ts_xlib.h"
-#include "x11drv.h"
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <signal.h>
 #include <sys/stat.h>
 #include <unistd.h>
+
 #include "winbase.h"
 #include "class.h"
 #include "module.h"
@@ -30,6 +27,7 @@
 #include "process.h"
 #include "main.h"
 #include "expr.h"
+#include "user.h"
 
 extern FILE * yyin;
 unsigned int dbg_mode = 0;
@@ -494,9 +492,7 @@
         GlobalUnlock16( GetCurrentTask() );
 
         /* Put the display in a correct state */
-
-        TSXUngrabServer( display );
-        TSXFlush( display );
+	USER_Driver->pBeginDebugging();
 
         newmode = ISV86(&DEBUG_context) ? 16 : IS_SELECTOR_32BIT(addr.seg) ? 32 : 16;
         if (newmode != dbg_mode)
@@ -569,6 +565,8 @@
       }
 
     in_debugger = FALSE;
+
+    USER_Driver->pEndDebugging();
 }
 
 
diff --git a/graphics/metafiledrv/init.c b/graphics/metafiledrv/init.c
index 197d5d5..c7195d3 100644
--- a/graphics/metafiledrv/init.c
+++ b/graphics/metafiledrv/init.c
@@ -24,6 +24,8 @@
     NULL,                            /* pCreateBitmap */
     NULL, /* no implementation */    /* pCreateDC */
     NULL, /* no implementation */    /* pDeleteDC */
+    NULL,                            /* pCreateDIBSection */
+    NULL,                            /* pCreateDIBSection16 */
     NULL,                            /* pDeleteObject */
     MFDRV_Ellipse,                   /* pEllipse */
     NULL,                            /* pEnumDeviceFonts */
diff --git a/graphics/psdrv/init.c b/graphics/psdrv/init.c
index aa4cac7..b12ff68 100644
--- a/graphics/psdrv/init.c
+++ b/graphics/psdrv/init.c
@@ -27,6 +27,8 @@
     NULL,                            /* pCreateBitmap */
     PSDRV_CreateDC,                  /* pCreateDC */
     PSDRV_DeleteDC,                  /* pDeleteDC */
+    NULL,                            /* pCreateDIBSection */
+    NULL,                            /* pCreateDIBSection16 */
     NULL,                            /* pDeleteObject */
     PSDRV_Ellipse,                   /* pEllipse */
     PSDRV_EnumDeviceFonts,           /* pEnumDeviceFonts */
diff --git a/graphics/ttydrv/Makefile.in b/graphics/ttydrv/Makefile.in
index 662e548..d667c9f 100644
--- a/graphics/ttydrv/Makefile.in
+++ b/graphics/ttydrv/Makefile.in
@@ -6,7 +6,9 @@
 MODULE    = ttydrv
 
 C_SRCS = \
-	init.c
+	bitmap.c \
+	init.c \
+	palette.c
 
 all: $(MODULE).o
 
diff --git a/graphics/ttydrv/bitmap.c b/graphics/ttydrv/bitmap.c
new file mode 100644
index 0000000..94c3cd8
--- /dev/null
+++ b/graphics/ttydrv/bitmap.c
@@ -0,0 +1,56 @@
+/*
+ * TTY bitmap driver
+ *
+ * Copyright 1999 Patrik Stridvall
+ */
+
+#include "dc.h"
+#include "bitmap.h"
+#include "ttydrv.h"
+
+/**********************************************************************
+ *		TTYDRV_BITMAP_CreateDIBSection
+ */
+HBITMAP TTYDRV_BITMAP_CreateDIBSection(
+  DC *dc, BITMAPINFO *bmi, UINT usage, 
+  LPVOID *bits, HANDLE section, DWORD offset)
+{
+  return (HBITMAP) NULL;
+}
+
+/**********************************************************************
+ *		TTYDRV_BITMAP_CreateDIBSection16
+ */
+HBITMAP16 TTYDRV_DIB_CreateDIBSection16(
+  DC *dc, BITMAPINFO *bmi, UINT16 usage,
+  SEGPTR *bits, HANDLE section, DWORD offset)
+{
+  return (HBITMAP16) NULL;
+}
+
+/**********************************************************************
+ *		TTYDRV_BITMAP_SetDIBits
+ */
+INT TTYDRV_BITMAP_SetDIBits(
+  BITMAPOBJ *bmp, DC *dc, UINT startscan, UINT lines, 
+  LPCVOID bits, const BITMAPINFO *info, UINT coloruse, HBITMAP hbitmap)
+{
+  return 0;
+}
+
+/**********************************************************************
+ *		TTYDRV_BITMAP_GetDIBits
+ */
+INT TTYDRV_BITMAP_GetDIBits(
+  BITMAPOBJ *bmp, DC *dc, UINT startscan, UINT lines, 
+  LPVOID bits, BITMAPINFO *info, UINT coloruse, HBITMAP hbitmap)
+{
+  return 0;
+}
+
+/**********************************************************************
+ *		TTYDRV_BITMAP_DeleteDIBSection
+ */
+void TTYDRV_BITMAP_DeleteDIBSection(BITMAPOBJ *bmp)
+{
+}
diff --git a/graphics/ttydrv/init.c b/graphics/ttydrv/init.c
index 5f4dcf4..680419a 100644
--- a/graphics/ttydrv/init.c
+++ b/graphics/ttydrv/init.c
@@ -4,25 +4,30 @@
  * Copyright 1998 Patrik Stridvall
  */
 
+#include "gdi.h"
+#include "bitmap.h"
 #include "color.h"
 #include "dc.h"
 #include "debug.h"
 #include "heap.h"
+#include "palette.h"
 #include "ttydrv.h"
 
-static const DC_FUNCTIONS TTYDRV_GDI_Driver =
+static const DC_FUNCTIONS TTYDRV_DC_Driver =
 {
   NULL,                /* pArc */
   NULL,                /* pBitBlt */
   NULL,                /* pBitmapBits */
   NULL,                /* pChord */
   NULL,                /* pCreateBitmap */
-  TTYDRV_GDI_CreateDC, /* pCreateDC */
-  TTYDRV_GDI_DeleteDC, /* pDeleteDC */
+  TTYDRV_DC_CreateDC,  /* pCreateDC */
+  TTYDRV_DC_DeleteDC,  /* pDeleteDC */
+  NULL,                /* pCreateDIBSection */
+  NULL,                /* pCreateDIBSection16 */
   NULL,                /* pDeleteObject */
   NULL,                /* pEllipse */
   NULL,                /* pEnumDeviceFonts */
-  TTYDRV_GDI_Escape,   /* pEscape */
+  TTYDRV_DC_Escape,    /* pEscape */
   NULL,                /* pExcludeClipRect */
   NULL,                /* pExcludeVisRect */
   NULL,                /* pExtFloodFill */
@@ -80,9 +85,29 @@
   NULL                 /* pStretchDIBits */
 };
 
+
+GDI_DRIVER TTYDRV_GDI_Driver =
+{
+  TTYDRV_GDI_Initialize,
+  TTYDRV_GDI_Finalize
+};
+
+BITMAP_DRIVER TTYDRV_BITMAP_Driver =
+{
+  TTYDRV_BITMAP_SetDIBits,
+  TTYDRV_BITMAP_GetDIBits,
+  TTYDRV_BITMAP_DeleteDIBSection
+};
+
+PALETTE_DRIVER TTYDRV_PALETTE_Driver = 
+{
+  TTYDRV_PALETTE_SetMapping,
+  TTYDRV_PALETTE_UpdateMapping
+};
+
 /* FIXME: Adapt to the TTY driver. Copied from the X11 driver */
 
-static DeviceCaps TTYDRV_GDI_DevCaps = {
+static DeviceCaps TTYDRV_DC_DevCaps = {
 /* version */		0, 
 /* technology */	DT_RASDISPLAY,
 /* size, resolution */	0, 0, 0, 0, 0, 
@@ -110,37 +135,41 @@
  */
 BOOL TTYDRV_GDI_Initialize(void)
 {
+  BITMAP_Driver = &TTYDRV_BITMAP_Driver;
+  PALETTE_Driver = &TTYDRV_PALETTE_Driver;
 
-  TTYDRV_GDI_DevCaps.version = 0x300;
-  TTYDRV_GDI_DevCaps.horzSize = 0;    /* FIXME: Screen width in mm */
-  TTYDRV_GDI_DevCaps.vertSize = 0;    /* FIXME: Screen height in mm */
-  TTYDRV_GDI_DevCaps.horzRes = 640;   /* FIXME: Screen width in pixel */
-  TTYDRV_GDI_DevCaps.vertRes = 480;   /* FIXME: Screen height in pixel */
-  TTYDRV_GDI_DevCaps.bitsPixel = 1;   /* FIXME: Bits per pixel */
-  TTYDRV_GDI_DevCaps.sizePalette = 0; /* FIXME: ??? */
+  TTYDRV_DC_DevCaps.version = 0x300;
+  TTYDRV_DC_DevCaps.horzSize = 0;    /* FIXME: Screen width in mm */
+  TTYDRV_DC_DevCaps.vertSize = 0;    /* FIXME: Screen height in mm */
+  TTYDRV_DC_DevCaps.horzRes = 640;   /* FIXME: Screen width in pixel */
+  TTYDRV_DC_DevCaps.vertRes = 480;   /* FIXME: Screen height in pixel */
+  TTYDRV_DC_DevCaps.bitsPixel = 1;   /* FIXME: Bits per pixel */
+  TTYDRV_DC_DevCaps.sizePalette = 0; /* FIXME: ??? */
   
   /* Resolution will be adjusted during the font init */
   
-  TTYDRV_GDI_DevCaps.logPixelsX = (int) (TTYDRV_GDI_DevCaps.horzRes * 25.4 / TTYDRV_GDI_DevCaps.horzSize);
-  TTYDRV_GDI_DevCaps.logPixelsY = (int) (TTYDRV_GDI_DevCaps.vertRes * 25.4 / TTYDRV_GDI_DevCaps.vertSize);
+  TTYDRV_DC_DevCaps.logPixelsX = (int) (TTYDRV_DC_DevCaps.horzRes * 25.4 / TTYDRV_DC_DevCaps.horzSize);
+  TTYDRV_DC_DevCaps.logPixelsY = (int) (TTYDRV_DC_DevCaps.vertRes * 25.4 / TTYDRV_DC_DevCaps.vertSize);
  
-  if( !COLOR_Init() ) return FALSE;
+  if(!TTYDRV_PALETTE_Initialize())
+    return FALSE;
 
-  return DRIVER_RegisterDriver( "DISPLAY", &TTYDRV_GDI_Driver );
+  return DRIVER_RegisterDriver( "DISPLAY", &TTYDRV_DC_Driver );
 }
 
 /**********************************************************************
  *	     TTYDRV_GDI_Finalize
  */
-void TTDRV_GDI_Finalize()
+void TTYDRV_GDI_Finalize(void)
 {
+    TTYDRV_PALETTE_Finalize();
 }
 
 /**********************************************************************
- *	     TTYDRV_GDI_CreateDC
+ *	     TTYDRV_DC_CreateDC
  */
-BOOL TTYDRV_GDI_CreateDC(DC *dc, LPCSTR driver, LPCSTR device,
-			   LPCSTR output, const DEVMODE16 *initData)
+BOOL TTYDRV_DC_CreateDC(DC *dc, LPCSTR driver, LPCSTR device,
+			    LPCSTR output, const DEVMODE16 *initData)
 {
   FIXME(ttydrv, "(%p, %s, %s, %s, %p): semistub\n",
     dc, debugstr_a(driver), debugstr_a(device), 
@@ -155,16 +184,16 @@
     return FALSE;
   }
 
-  dc->w.devCaps = &TTYDRV_GDI_DevCaps;
+  dc->w.devCaps = &TTYDRV_DC_DevCaps;
   
   return TRUE;
 }
 
 
 /**********************************************************************
- *	     TTYDRV_GDI_DeleteDC
+ *	     TTYDRV_DC_DeleteDC
  */
-BOOL TTYDRV_GDI_DeleteDC(DC *dc)
+BOOL TTYDRV_DC_DeleteDC(DC *dc)
 {
   FIXME(ttydrv, "(%p): semistub\n", dc);
 
@@ -175,11 +204,10 @@
 }
 
 /**********************************************************************
- *           TTYDRV_GDI_Escape
+ *           TTYDRV_DC_Escape
  */
-INT TTYDRV_GDI_Escape(DC *dc, INT nEscape, INT cbInput,
-			SEGPTR lpInData, SEGPTR lpOutData)
+INT TTYDRV_DC_Escape(DC *dc, INT nEscape, INT cbInput,
+			 SEGPTR lpInData, SEGPTR lpOutData)
 {
     return 0;
 }
-
diff --git a/graphics/ttydrv/palette.c b/graphics/ttydrv/palette.c
new file mode 100644
index 0000000..55cd2fa
--- /dev/null
+++ b/graphics/ttydrv/palette.c
@@ -0,0 +1,41 @@
+/*
+ * TTY palette driver
+ *
+ * Copyright 1999 Patrik Stridvall
+ */
+
+#include "palette.h"
+#include "ttydrv.h"
+
+/**********************************************************************
+ *	     TTYDRV_PALETTE_Initialize
+ */
+BOOL TTYDRV_PALETTE_Initialize(void)
+{
+  return TRUE;
+}
+
+/**********************************************************************
+ *	     TTYDRV_PALETTE_Finalize
+ *
+ */
+void TTYDRV_PALETTE_Finalize(void)
+{
+}
+
+/***********************************************************************
+ *           TTYDRV_PALETTE_SetMapping
+ */
+int TTYDRV_PALETTE_SetMapping(
+  PALETTEOBJ *palPtr, UINT uStart, UINT uNum, BOOL mapOnly)
+{
+  return 0;
+}
+
+/***********************************************************************
+ *           TTYDRV_PALETTE_UpdateMapping
+ */
+int TTYDRV_PALETTE_UpdateMapping(PALETTEOBJ *palPtr)
+{
+  return 0;
+}
diff --git a/graphics/win16drv/init.c b/graphics/win16drv/init.c
index d8ae969..f8f9b7e 100644
--- a/graphics/win16drv/init.c
+++ b/graphics/win16drv/init.c
@@ -49,6 +49,8 @@
     NULL,                            /* pCreateBitmap */
     WIN16DRV_CreateDC,               /* pCreateDC */
     NULL,                            /* pDeleteDC */
+    NULL,                            /* pCreateDIBSection */
+    NULL,                            /* pCreateDIBSection16 */
     NULL,                            /* pDeleteObject */
     WIN16DRV_Ellipse,                /* pEllipse */
     WIN16DRV_EnumDeviceFonts,        /* pEnumDeviceFonts */
diff --git a/graphics/wing.c b/graphics/wing.c
index 2eac606..fd30439 100644
--- a/graphics/wing.c
+++ b/graphics/wing.c
@@ -6,28 +6,19 @@
 
 #include "config.h"
 
-#include "ts_xlib.h"
-#ifdef HAVE_LIBXXSHM
-#include <sys/types.h>
-#include <sys/ipc.h>
-#ifndef __EMX__
-#include <sys/shm.h>
-#endif /* !defined(__EMX__) */
-#include "ts_xshm.h"
-#endif /* defined(HAVE_LIBXXSHM) */
+#ifndef X_DISPLAY_MISSING
 #include "x11drv.h"
+#endif /* !defined(X_DISPLAY_MISSING) */
 
 #include "wine/winuser16.h"
 #include "bitmap.h"
-#include "palette.h"
-#include "dc.h"
 #include "debug.h"
-#include "gdi.h"
-#include "heap.h"
-#include "selectors.h"
+#include "ldt.h"
 #include "monitor.h"
+#include "palette.h"
 #include "windef.h"
-#include "xmalloc.h"
+#include "wine/winuser16.h"
+
 
 typedef enum WING_DITHER_TYPE
 {
@@ -105,7 +96,11 @@
     if (bmpi)
 	FIXME(wing, ": Todo - implement setting BITMAPINFO\n");
 
-    return PTR_SEG_OFF_TO_SEGPTR(bmp->dib->selector, 0);
+#ifndef X_DISPLAY_MISSING
+    return PTR_SEG_OFF_TO_SEGPTR(((X11DRV_DIBSECTION *) bmp->dib)->selector, 0);
+#else /* !defined(X_DISPLAY_MISSING) */
+    return NULL;
+#endif /* !defined(X_DISPLAY_MISSING) */
 }
 
 /***********************************************************************
diff --git a/graphics/x11drv/Makefile.in b/graphics/x11drv/Makefile.in
index 0d1a1fa..679ad08 100644
--- a/graphics/x11drv/Makefile.in
+++ b/graphics/x11drv/Makefile.in
@@ -15,6 +15,7 @@
 	init.c \
 	objects.c \
 	oembitmap.c \
+	palette.c \
 	pen.c \
 	text.c \
 	xfont.c
diff --git a/graphics/x11drv/bitblt.c b/graphics/x11drv/bitblt.c
index 4eb220e..d15abc5 100644
--- a/graphics/x11drv/bitblt.c
+++ b/graphics/x11drv/bitblt.c
@@ -596,11 +596,11 @@
     pdata += swap ? start+width-1 : start;
     if (image->depth == depthDst)  /* color -> color */
     {
-        if (COLOR_PixelToPalette && (depthDst != 1))
+        if (X11DRV_PALETTE_XPixelToPalette && (depthDst != 1))
             if (swap) for (i = 0; i < width; i++)
-                *pdata-- = COLOR_PixelToPalette[XGetPixel( image, i, row )];
+                *pdata-- = X11DRV_PALETTE_XPixelToPalette[XGetPixel( image, i, row )];
             else for (i = 0; i < width; i++)
-                *pdata++ = COLOR_PixelToPalette[XGetPixel( image, i, row )];
+                *pdata++ = X11DRV_PALETTE_XPixelToPalette[XGetPixel( image, i, row )];
         else
             if (swap) for (i = 0; i < width; i++)
                 *pdata-- = XGetPixel( image, i, row );
@@ -611,10 +611,10 @@
     {
         if (image->depth == 1)  /* monochrome -> color */
         {
-            if (COLOR_PixelToPalette)
+            if (X11DRV_PALETTE_XPixelToPalette)
             {
-                fg = COLOR_PixelToPalette[fg];
-                bg = COLOR_PixelToPalette[bg];
+                fg = X11DRV_PALETTE_XPixelToPalette[fg];
+                bg = X11DRV_PALETTE_XPixelToPalette[bg];
             }
             if (swap) for (i = 0; i < width; i++)
                 *pdata-- = XGetPixel( image, i, row ) ? bg : fg;
@@ -873,7 +873,7 @@
 
     if (dcSrc->w.bitsPerPixel == dcDst->w.bitsPerPixel)
     {
-        if (!COLOR_PixelToPalette ||
+        if (!X11DRV_PALETTE_XPixelToPalette ||
             (dcDst->w.bitsPerPixel == 1))  /* monochrome -> monochrome */
         {
             XCopyArea( display, physDevSrc->drawable, pixmap, gc,
@@ -897,7 +897,7 @@
             for (y = 0; y < height; y++)
                 for (x = 0; x < width; x++)
                     XPutPixel(imageSrc, x, y,
-                              COLOR_PixelToPalette[XGetPixel(imageSrc, x, y)]);
+                              X11DRV_PALETTE_XPixelToPalette[XGetPixel(imageSrc, x, y)]);
             XPutImage( display, pixmap, gc, imageSrc,
                        0, 0, 0, 0, width, height );
             XDestroyImage( imageSrc );
@@ -907,12 +907,12 @@
     {
         if (dcSrc->w.bitsPerPixel == 1)  /* monochrome -> color */
         {
-            if (COLOR_PixelToPalette)
+            if (X11DRV_PALETTE_XPixelToPalette)
             {
                 XSetBackground( display, gc, 
-                             COLOR_PixelToPalette[physDevDst->textPixel] );
+                             X11DRV_PALETTE_XPixelToPalette[physDevDst->textPixel] );
                 XSetForeground( display, gc,
-                             COLOR_PixelToPalette[physDevDst->backgroundPixel]);
+                             X11DRV_PALETTE_XPixelToPalette[physDevDst->backgroundPixel]);
             }
             else
             {
@@ -955,8 +955,8 @@
     INT height = visRectDst->bottom - visRectDst->top;
     X11DRV_PDEVICE *physDev = (X11DRV_PDEVICE *)dc->physDev;
 
-    if (!COLOR_PixelToPalette || (dc->w.bitsPerPixel == 1) ||
-	(COLOR_GetSystemPaletteFlags() & COLOR_VIRTUAL) )
+    if (!X11DRV_PALETTE_XPixelToPalette || (dc->w.bitsPerPixel == 1) ||
+	(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) )
     {
         XCopyArea( display, physDev->drawable, pixmap, gc,
                    visRectDst->left, visRectDst->top, width, height, 0, 0 );
@@ -981,7 +981,7 @@
         for (y = 0; y < height; y++)
             for (x = 0; x < width; x++)
                 XPutPixel( image, x, y,
-                           COLOR_PixelToPalette[XGetPixel( image, x, y )]);
+                           X11DRV_PALETTE_XPixelToPalette[XGetPixel( image, x, y )]);
         XPutImage( display, pixmap, gc, image, 0, 0, 0, 0, width, height );
 	XDestroyImage( image );
     }
@@ -1000,10 +1000,10 @@
     INT height = visRectDst->bottom - visRectDst->top;
     X11DRV_PDEVICE *physDev = (X11DRV_PDEVICE *)dc->physDev;
 
-    /* !COLOR_PaletteToPixel is _NOT_ enough */
+    /* !X11DRV_PALETTE_PaletteToXPixel is _NOT_ enough */
 
-    if (!COLOR_PaletteToPixel || (dc->w.bitsPerPixel == 1) || 
-        (COLOR_GetSystemPaletteFlags() & COLOR_VIRTUAL) )
+    if (!X11DRV_PALETTE_PaletteToXPixel || (dc->w.bitsPerPixel == 1) || 
+        (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL) )
     {
         XCopyArea( display, pixmap, physDev->drawable, gc, 0, 0,
                    width, height, visRectDst->left, visRectDst->top );
@@ -1017,7 +1017,7 @@
             for (x = 0; x < width; x++)
             {
                 XPutPixel( image, x, y,
-                           COLOR_PaletteToPixel[XGetPixel( image, x, y )]);
+                           X11DRV_PALETTE_PaletteToXPixel[XGetPixel( image, x, y )]);
             }
         XPutImage( display, physDev->drawable, gc, image, 0, 0,
                    visRectDst->left, visRectDst->top, width, height );
@@ -1192,12 +1192,12 @@
     if (!fStretch) switch(rop)  /* A few optimisations */
     {
     case BLACKNESS:  /* 0x00 */
-        if ((dcDst->w.bitsPerPixel == 1) || !COLOR_PaletteToPixel)
+        if ((dcDst->w.bitsPerPixel == 1) || !X11DRV_PALETTE_PaletteToXPixel)
             XSetFunction( display, physDevDst->gc, GXclear );
         else
         {
             XSetFunction( display, physDevDst->gc, GXcopy );
-            XSetForeground( display, physDevDst->gc, COLOR_PaletteToPixel[0] );
+            XSetForeground( display, physDevDst->gc, X11DRV_PALETTE_PaletteToXPixel[0] );
             XSetFillStyle( display, physDevDst->gc, FillSolid );
         }
         XFillRectangle( display, physDevDst->drawable, physDevDst->gc,
@@ -1205,12 +1205,12 @@
         return TRUE;
 
     case DSTINVERT:  /* 0x55 */
-        if ((dcDst->w.bitsPerPixel == 1) || !COLOR_PaletteToPixel ||
+        if ((dcDst->w.bitsPerPixel == 1) || !X11DRV_PALETTE_PaletteToXPixel ||
             !Options.perfectGraphics)
         {
             XSetFunction( display, physDevDst->gc, GXinvert );
 
-            if( COLOR_GetSystemPaletteFlags() & (COLOR_PRIVATE | COLOR_VIRTUAL) )
+            if( X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_PRIVATE | X11DRV_PALETTE_VIRTUAL) )
                 XSetFunction( display, physDevDst->gc, GXinvert);
             else
             {
@@ -1287,13 +1287,13 @@
         return TRUE;
 
     case WHITENESS:  /* 0xff */
-        if ((dcDst->w.bitsPerPixel == 1) || !COLOR_PaletteToPixel)
+        if ((dcDst->w.bitsPerPixel == 1) || !X11DRV_PALETTE_PaletteToXPixel)
             XSetFunction( display, physDevDst->gc, GXset );
         else
         {
             XSetFunction( display, physDevDst->gc, GXcopy );
             XSetForeground( display, physDevDst->gc, 
-                            COLOR_PaletteToPixel[COLOR_GetSystemPaletteSize() - 1]);
+                            X11DRV_PALETTE_PaletteToXPixel[X11DRV_DevCaps.sizePalette - 1]);
             XSetFillStyle( display, physDevDst->gc, FillSolid );
         }
         XFillRectangle( display, physDevDst->drawable, physDevDst->gc,
@@ -1407,11 +1407,11 @@
     struct StretchBlt_params params = { dc, left, top, width, height,
                                         NULL, 0, 0, 0, 0, rop };
     BOOL result;
-    DIB_UpdateDIBSection( dc, FALSE );
+    X11DRV_DIB_UpdateDIBSection( dc, FALSE );
     EnterCriticalSection( &X11DRV_CritSection );
     result = (BOOL)CALL_LARGE_STACK( BITBLT_DoStretchBlt, &params );
     LeaveCriticalSection( &X11DRV_CritSection );
-    DIB_UpdateDIBSection( dc, TRUE );
+    X11DRV_DIB_UpdateDIBSection( dc, TRUE );
     return result;
 }
 
@@ -1426,12 +1426,12 @@
     struct StretchBlt_params params = { dcDst, xDst, yDst, width, height,
                                         dcSrc, xSrc, ySrc, width, height, rop};
     BOOL result;
-    DIB_UpdateDIBSection( dcDst, FALSE );
-    DIB_UpdateDIBSection( dcSrc, FALSE );
+    X11DRV_DIB_UpdateDIBSection( dcDst, FALSE );
+    X11DRV_DIB_UpdateDIBSection( dcSrc, FALSE );
     EnterCriticalSection( &X11DRV_CritSection );
     result = (BOOL)CALL_LARGE_STACK( BITBLT_DoStretchBlt, &params );
     LeaveCriticalSection( &X11DRV_CritSection );
-    DIB_UpdateDIBSection( dcDst, TRUE );
+    X11DRV_DIB_UpdateDIBSection( dcDst, TRUE );
     return result;
 }
 
@@ -1448,12 +1448,12 @@
                                         dcSrc, xSrc, ySrc, widthSrc, heightSrc,
                                         rop };
     BOOL result;
-    DIB_UpdateDIBSection( dcDst, FALSE );
-    DIB_UpdateDIBSection( dcSrc, FALSE );
+    X11DRV_DIB_UpdateDIBSection( dcDst, FALSE );
+    X11DRV_DIB_UpdateDIBSection( dcSrc, FALSE );
     EnterCriticalSection( &X11DRV_CritSection );
     result = (BOOL)CALL_LARGE_STACK( BITBLT_DoStretchBlt, &params );
     LeaveCriticalSection( &X11DRV_CritSection );
-    DIB_UpdateDIBSection( dcDst, TRUE );
+    X11DRV_DIB_UpdateDIBSection( dcDst, TRUE );
     return result;
 }
 
diff --git a/graphics/x11drv/brush.c b/graphics/x11drv/brush.c
index a28104c..cb564d7 100644
--- a/graphics/x11drv/brush.c
+++ b/graphics/x11drv/brush.c
@@ -88,7 +88,7 @@
 };
 
 #define PIXEL_VALUE(r,g,b) \
-    COLOR_mapEGAPixel[EGAmapping[((r)*PRIMARY_LEVELS+(g))*PRIMARY_LEVELS+(b)]]
+    X11DRV_PALETTE_mapEGAPixel[EGAmapping[((r)*PRIMARY_LEVELS+(g))*PRIMARY_LEVELS+(b)]]
 
   /* X image for building dithered pixmap */
 static XImage *ditherImage = NULL;
@@ -163,7 +163,7 @@
     else
     {
 	  /* Solid brush */
-	physDev->brush.pixel = COLOR_ToPhysical( dc, color );
+	physDev->brush.pixel = X11DRV_PALETTE_ToPhysical( dc, color );
 	physDev->brush.fillStyle = FillSolid;
     }
 }
@@ -258,7 +258,7 @@
 	
       case BS_HATCHED:
 	TRACE(gdi, "BS_HATCHED\n" );
-	physDev->brush.pixel = COLOR_ToPhysical( dc, brush->logbrush.lbColor );
+	physDev->brush.pixel = X11DRV_PALETTE_ToPhysical( dc, brush->logbrush.lbColor );
 	physDev->brush.pixmap = TSXCreateBitmapFromData( display, X11DRV_GetXRootWindow(),
 				 HatchBrushes[brush->logbrush.lbHatch], 8, 8 );
 	physDev->brush.fillStyle = FillStippled;
diff --git a/graphics/x11drv/dib.c b/graphics/x11drv/dib.c
index 53d72d9..140c4e0 100644
--- a/graphics/x11drv/dib.c
+++ b/graphics/x11drv/dib.c
@@ -18,7 +18,9 @@
 #include "dc.h"
 #include "color.h"
 #include "callback.h"
-#include "xmalloc.h"
+#include "selectors.h"
+#include "global.h"
+#include "xmalloc.h" /* for XCREATEIMAGE macro */
 
 static int bitmapDepthTable[] = { 8, 1, 32, 16, 24, 15, 4, 0 };
 static int ximageDepthTable[] = { 0, 0, 0,  0,  0,  0,  0 };
@@ -111,7 +113,7 @@
                                        rgb->rgbBlue > 255*3/2);
             else
                 for (i = 0; i < colors; i++, rgb++)
-                    colorMapping[i] = COLOR_ToPhysical( dc, RGB(rgb->rgbRed,
+                    colorMapping[i] = X11DRV_PALETTE_ToPhysical( dc, RGB(rgb->rgbRed,
                                                                 rgb->rgbGreen,
                                                                 rgb->rgbBlue));
         }
@@ -125,7 +127,7 @@
                                        rgb->rgbtBlue > 255*3/2);
             else
                 for (i = 0; i < colors; i++, rgb++)
-                    colorMapping[i] = COLOR_ToPhysical( dc, RGB(rgb->rgbtRed,
+                    colorMapping[i] = X11DRV_PALETTE_ToPhysical( dc, RGB(rgb->rgbtRed,
                                                                rgb->rgbtGreen,
                                                                rgb->rgbtBlue));
         }
@@ -133,7 +135,7 @@
     else  /* DIB_PAL_COLORS */
     {
         for (i = 0; i < colors; i++, colorPtr++)
-            colorMapping[i] = COLOR_ToPhysical( dc, PALETTEINDEX(*colorPtr) );
+            colorMapping[i] = X11DRV_PALETTE_ToPhysical( dc, PALETTEINDEX(*colorPtr) );
     }
 
     *nColors = colors;
@@ -705,7 +707,7 @@
 		g = (BYTE) ((val & 0x03e0) >> 2);
 		b = (BYTE) ((val & 0x001f) << 3);
 		XPutPixel( bmpImage, x, h,
-			   COLOR_ToPhysical(dc, RGB(r,g,b)) );
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(r,g,b)) );
 	    }
 	    ptr = (LPWORD) (srcbits += linebytes) + left;
 	}
@@ -718,7 +720,7 @@
 		g = (BYTE) ((val & 0x03e0) >> 2);
 		b = (BYTE) ((val & 0x001f) << 3);
 		XPutPixel( bmpImage, x, h,
-			   COLOR_ToPhysical(dc, RGB(r,g,b)) );
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(r,g,b)) );
 	    }
 	    ptr = (LPWORD) (srcbits += linebytes) + left;
 	}
@@ -751,7 +753,7 @@
         {
            for (x = left; x < dstwidth; x++, ptr++)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                r = (BYTE) GetRValue(pixel);
                g = (BYTE) GetGValue(pixel);
                b = (BYTE) GetBValue(pixel);
@@ -765,7 +767,7 @@
         {
            for (x = left; x < dstwidth; x++, ptr++)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                r = (BYTE) GetRValue(pixel);
                g = (BYTE) GetGValue(pixel);
                b = (BYTE) GetBValue(pixel);
@@ -803,7 +805,7 @@
 	for (h = lines - 1; h >= 0; h--) {
 	    for (x = left; x < dstwidth; x++, bits += 3) {
 		XPutPixel( bmpImage, x, h, 
-			   COLOR_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
 	    }
 	    bits = (srcbits += linebytes) + left * 3;
 	}
@@ -812,7 +814,7 @@
 	for (h = 0; h < lines; h++) {
 	    for (x = left; x < dstwidth; x++, bits += 3) {
 		XPutPixel( bmpImage, x, h,
-			   COLOR_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
 	    }
 	    bits = (srcbits += linebytes) + left * 3;
 	}
@@ -843,7 +845,7 @@
         {
            for (x = left; x < dstwidth; x++, bits += 3)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                 bits[0] = GetRValue(pixel);
                 bits[1] = GetGValue(pixel);
                 bits[2] = GetBValue(pixel);
@@ -856,7 +858,7 @@
         {
            for (x = left; x < dstwidth; x++, bits += 3)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                 bits[0] = GetRValue(pixel);
                 bits[1] = GetGValue(pixel);
                 bits[2] = GetBValue(pixel);
@@ -889,7 +891,7 @@
 	for (h = lines - 1; h >= 0; h--) {
 	    for (x = left; x < dstwidth; x++, bits += 4) {
 		XPutPixel( bmpImage, x, h, 
-			   COLOR_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
 	    }
 	    bits = (srcbits += linebytes) + left * 4;
 	}
@@ -898,7 +900,7 @@
 	for (h = 0; h < lines; h++) {
 	    for (x = left; x < dstwidth; x++, bits += 4) {
 		XPutPixel( bmpImage, x, h,
-			   COLOR_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
+			   X11DRV_PALETTE_ToPhysical(dc, RGB(bits[2],bits[1],bits[0])));
 	    }
 	    bits = (srcbits += linebytes) + left * 4;
 	}
@@ -929,7 +931,7 @@
         {
            for (x = left; x < dstwidth; x++, bits += 4)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                 bits[0] = GetRValue(pixel);
                 bits[1] = GetGValue(pixel);
                 bits[2] = GetBValue(pixel);
@@ -942,7 +944,7 @@
         {
            for (x = left; x < dstwidth; x++, bits += 4)
             {
-                COLORREF pixel = COLOR_ToLogical( XGetPixel( bmpImage, x, h ) );
+                COLORREF pixel = X11DRV_PALETTE_ToLogical( XGetPixel( bmpImage, x, h ) );
                 bits[0] = GetRValue(pixel);
                 bits[1] = GetGValue(pixel);
                 bits[2] = GetBValue(pixel);
@@ -961,7 +963,7 @@
  * Helper function for SetDIBits() and SetDIBitsToDevice().
  * The Xlib critical section must be entered before calling this function.
  */
-int X11DRV_DIB_SetImageBits( const DIB_SETIMAGEBITS_DESCR *descr )
+int X11DRV_DIB_SetImageBits( const X11DRV_DIB_SETIMAGEBITS_DESCR *descr )
 {
     int lines = descr->lines >= 0 ? descr->lines : -descr->lines;
     XImage *bmpImage;
@@ -1046,7 +1048,7 @@
  * Transfer the bits from an X image.
  * The Xlib critical section must be entered before calling this function.
  */
-int X11DRV_DIB_GetImageBits( const DIB_SETIMAGEBITS_DESCR *descr )
+int X11DRV_DIB_GetImageBits( const X11DRV_DIB_SETIMAGEBITS_DESCR *descr )
 {
     int lines = descr->lines >= 0 ? descr->lines : -descr->lines;
     XImage *bmpImage;
@@ -1130,7 +1132,7 @@
 				UINT startscan, UINT lines, LPCVOID bits,
 				const BITMAPINFO *info, UINT coloruse )
 {
-    DIB_SETIMAGEBITS_DESCR descr;
+    X11DRV_DIB_SETIMAGEBITS_DESCR descr;
     DWORD width, oldcy = cy;
     INT result;
     int height, tmpheight;
@@ -1188,4 +1190,865 @@
     return result;
 }
 
+/***********************************************************************
+ *           X11DRV_DIB_SetDIBits
+ */
+INT X11DRV_DIB_SetDIBits(
+  BITMAPOBJ *bmp, DC *dc, UINT startscan,
+  UINT lines, LPCVOID bits, const BITMAPINFO *info,
+  UINT coloruse, HBITMAP hbitmap)
+{
+  X11DRV_DIB_SETIMAGEBITS_DESCR descr;
+  X11DRV_PHYSBITMAP *pbitmap;
+  int height, tmpheight;
+  INT result;
+
+  descr.dc = dc;
+
+  if (DIB_GetBitmapInfo( &info->bmiHeader, &descr.infoWidth, &height,
+			 &descr.infoBpp, &descr.compression ) == -1)
+      return 0;
+
+  tmpheight = height;
+  if (height < 0) height = -height;
+  if (!lines || (startscan >= height))
+      return 0;
+
+  if (startscan + lines > height) lines = height - startscan;
+
+  if (descr.infoBpp <= 8)
+    {
+      descr.colorMap = X11DRV_DIB_BuildColorMap( descr.dc, coloruse,
+						 bmp->bitmap.bmBitsPixel,
+						 info, &descr.nColorMap );
+      if (!descr.colorMap)
+        {
+	  return 0;
+        } 
+    } else
+      descr.colorMap = 0;
+
+  /* HACK for now */
+  if(!bmp->DDBitmap)
+    X11DRV_CreateBitmap(hbitmap);
+
+  pbitmap = bmp->DDBitmap->physBitmap;
+  
+  descr.bits      = bits;
+  descr.image     = NULL;
+  descr.lines     = tmpheight >= 0 ? lines : -lines;
+  descr.depth     = bmp->bitmap.bmBitsPixel;
+  descr.drawable  = pbitmap->pixmap;
+  descr.gc        = BITMAP_GC(bmp);
+  descr.xSrc      = 0;
+  descr.ySrc      = 0;
+  descr.xDest     = 0;
+  descr.yDest     = height - startscan - lines;
+  descr.width     = bmp->bitmap.bmWidth;
+  descr.height    = lines;
+  
+  EnterCriticalSection( &X11DRV_CritSection );
+  result = CALL_LARGE_STACK( X11DRV_DIB_SetImageBits, &descr );
+  LeaveCriticalSection( &X11DRV_CritSection );
+  
+  if (descr.colorMap) HeapFree(GetProcessHeap(), 0, descr.colorMap);
+
+  return result;
+}
+
+
+/*********************************************************************
+ *         X11DRV_DIB_GetNearestIndex
+ *
+ * Helper for X11DRV_DIB_GetDIBits.
+ * Returns the nearest colour table index for a given RGB.
+ * Nearest is defined by minimizing the sum of the squares.
+ */
+static INT X11DRV_DIB_GetNearestIndex(BITMAPINFO *info, BYTE r, BYTE g, BYTE b)
+{
+    INT i, best = -1, diff, bestdiff = -1;
+    RGBQUAD *color;
+
+    for(color = info->bmiColors, i = 0; i < (1 << info->bmiHeader.biBitCount);
+	color++, i++) {
+        diff = (r - color->rgbRed) * (r - color->rgbRed) +
+	       (g - color->rgbGreen) * (g - color->rgbGreen) +
+	       (b - color->rgbBlue) * (b - color->rgbBlue);
+	if(diff == 0)
+	    return i;
+	if(best == -1 || diff < bestdiff) {
+	    best = i;
+	    bestdiff = diff;
+	}
+    }
+    return best;
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_GetDIBits
+ */
+INT X11DRV_DIB_GetDIBits(
+  BITMAPOBJ *bmp, DC *dc, UINT startscan, 
+  UINT lines, LPVOID bits, BITMAPINFO *info,
+  UINT coloruse, HBITMAP hbitmap)
+{
+  XImage * bmpImage;
+  int x, y;
+  PALETTEENTRY * palEntry;
+  PALETTEOBJ * palette;
+  BYTE    *bbits = (BYTE*)bits, *linestart;
+  int	dstwidth, yend, xend = bmp->bitmap.bmWidth;
+  
+  TRACE(bitmap, "%u scanlines of (%i,%i) -> (%i,%i) starting from %u\n",
+	lines, bmp->bitmap.bmWidth, bmp->bitmap.bmHeight,
+	(int)info->bmiHeader.biWidth, (int)info->bmiHeader.biHeight,
+	startscan );
+
+  if (!(palette = (PALETTEOBJ*)GDI_GetObjPtr( dc->w.hPalette, PALETTE_MAGIC )))
+      return 0;
+
+  /* adjust number of scanlines to copy */
+  
+  if( lines > info->bmiHeader.biHeight )
+    lines = info->bmiHeader.biHeight;
+  
+  yend = startscan + lines;
+  if( startscan >= bmp->bitmap.bmHeight ) 
+    {
+      return FALSE;
+    }
+  if( yend > bmp->bitmap.bmHeight ) yend = bmp->bitmap.bmHeight;
+  
+  /* adjust scanline width */
+  
+  if(bmp->bitmap.bmWidth > info->bmiHeader.biWidth)
+    xend = info->bmiHeader.biWidth;
+  
+  /* HACK for now */
+  if(!bmp->DDBitmap)
+    X11DRV_CreateBitmap(hbitmap);
+  
+  dstwidth = DIB_GetDIBWidthBytes( info->bmiHeader.biWidth,
+				   info->bmiHeader.biBitCount );
+
+  EnterCriticalSection( &X11DRV_CritSection );
+  bmpImage = (XImage *)CALL_LARGE_STACK( X11DRV_BITMAP_GetXImage, bmp );
+  
+  linestart = bbits;
+  switch( info->bmiHeader.biBitCount ) {
+
+  case 1: /* 1 bit DIB */
+    {
+      unsigned long white = (1 << bmp->bitmap.bmBitsPixel) - 1;
+      
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  if (!(x&7)) *bbits = 0;
+	  *bbits |= (XGetPixel( bmpImage, x, y) >= white) 
+	    << (7 - (x&7));
+	  if ((x&7)==7) bbits++;
+	}
+	bbits = (linestart += dstwidth);
+      }
+    }
+    break;
+    
+    
+  case 4: /* 4 bit DIB */
+    switch(bmp->bitmap.bmBitsPixel) {
+      
+    case 1: /* 1/4 bit bmp -> 4 bit DIB */
+    case 4:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  if (!(x&1)) *bbits = 0;
+	  *bbits |= XGetPixel( bmpImage, x, y)<<(4*(1-(x&1)));
+	  if ((x&1)==1) bbits++;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 8: /* 8 bit bmp -> 4 bit DIB */
+      palEntry = palette->logpalette.palPalEntry;
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel = XGetPixel( bmpImage, x, y );
+	  if (!(x&1)) *bbits = 0;
+	  *bbits |= ( X11DRV_DIB_GetNearestIndex(info,
+						 palEntry[pixel].peRed,
+						 palEntry[pixel].peGreen,
+						 palEntry[pixel].peBlue )
+		      << (4*(1-(x&1))) );
+	  if ((x&1)==1) bbits++;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 15: /* 15/16 bit bmp -> 4 bit DIB */
+    case 16:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel = XGetPixel( bmpImage, x, y );
+	  if (!(x&1)) *bbits = 0;
+	  *bbits |= ( X11DRV_DIB_GetNearestIndex(info,
+						 ((pixel << 3) & 0xf8) |
+						 ((pixel >> 2) &  0x7),
+						 ((pixel >> 2) & 0xf8) |
+						 ((pixel >> 7) & 0x7),
+						 ((pixel >> 7) & 0xf8) |
+						 ((pixel >> 12) & 0x7) ) 
+		      << (4*(1-(x&1))) );
+	  if ((x&1)==1) bbits++;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 24: /* 24/32 bit bmp -> 4 bit DIB */
+    case 32:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel = XGetPixel( bmpImage, x, y );
+	  if (!(x&1)) *bbits = 0;
+	  *bbits |= ( X11DRV_DIB_GetNearestIndex( info,
+						  (pixel >> 16) & 0xff,
+						  (pixel >>  8) & 0xff,
+						  pixel & 0xff )
+		      << (4*(1-(x&1))) );
+	  if ((x&1)==1) bbits++;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+
+    default: /* ? bit bmp -> 4 bit DIB */
+      FIXME(bitmap, "4 bit DIB %d bit bitmap\n",
+	    bmp->bitmap.bmBitsPixel);
+      break;
+    }
+    break;
+
+
+  case 8: /* 8 bit DIB */
+    switch(bmp->bitmap.bmBitsPixel) {
+      
+    case 1: /* 1/4/8 bit bmp -> 8 bit DIB */
+    case 4:
+    case 8:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ )
+	  *bbits++ = XGetPixel( bmpImage, x, y );
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 15: /* 15/16 bit bmp -> 8 bit DIB */
+    case 16:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel = XGetPixel( bmpImage, x, y );
+	  *bbits++ = X11DRV_DIB_GetNearestIndex( info, 
+						 ((pixel << 3) & 0xf8) |
+						 ((pixel >> 2) &  0x7),
+						 ((pixel >> 2) & 0xf8) |
+						 ((pixel >> 7) & 0x7),
+						 ((pixel >> 7) & 0xf8) |
+						 ((pixel >> 12) & 0x7) );
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 24: /* 24/32 bit bmp -> 8 bit DIB */
+    case 32:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel = XGetPixel( bmpImage, x, y );
+	  *bbits++ = X11DRV_DIB_GetNearestIndex( info,
+						 (pixel >> 16) & 0xff,
+						 (pixel >>  8) & 0xff,
+						 pixel & 0xff );
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    default: /* ? bit bmp -> 8 bit DIB */
+      FIXME(bitmap, "8 bit DIB %d bit bitmap\n",
+	    bmp->bitmap.bmBitsPixel);
+      break;
+    }
+    break;
+    
+
+  case 15: /* 15/16 bit DIB */
+  case 16:
+    switch(bmp->bitmap.bmBitsPixel) {
+      
+    case 15: /* 15/16 bit bmp -> 16 bit DIB */
+    case 16:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = pixel & 0xff;
+	  *bbits++ = (pixel >> 8) & 0xff;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 24: /* 24/32 bit bmp -> 16 bit DIB */
+    case 32:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = ((pixel >> 6) & 0xe0) |
+	    ((pixel >> 3) & 0x1f);
+	  *bbits++ = ((pixel >> 17) & 0x7c) |
+	    ((pixel >> 14) & 0x3);
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 1: /* 1/4/8 bit bmp -> 16 bit DIB */
+    case 4:
+    case 8:
+      palEntry = palette->logpalette.palPalEntry;
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = ((palEntry[pixel].peBlue >> 3) & 0x1f) |
+	    ((palEntry[pixel].peGreen << 2) & 0xe0); 
+	  *bbits++ = ((palEntry[pixel].peGreen >> 6) & 0x3) |
+	    ((palEntry[pixel].peRed >> 1) & 0x7c);
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    default: /* ? bit bmp -> 16 bit DIB */
+      FIXME(bitmap, "15/16 bit DIB %d bit bitmap\n",
+	    bmp->bitmap.bmBitsPixel);
+      break;
+    }
+    break;
+    
+
+  case 24: /* 24 bit DIB */
+    switch(bmp->bitmap.bmBitsPixel) {
+      
+    case 24: /* 24/32 bit bmp -> 24 bit DIB */
+    case 32:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = (pixel >>16) & 0xff;
+	  *bbits++ = (pixel >> 8) & 0xff;
+	  *bbits++ =  pixel       & 0xff;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 15: /* 15/16 bit bmp -> 24 bit DIB */
+    case 16:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = ((pixel >> 7) & 0xf8) |
+	    ((pixel >> 12) & 0x7);
+	  *bbits++ = ((pixel >> 2) & 0xf8) |
+	    ((pixel >> 7) & 0x7);
+	  *bbits++ = ((pixel << 3) & 0xf8) |
+	    ((pixel >> 2) & 0x7);
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 1: /* 1/4/8 bit bmp -> 24 bit DIB */
+    case 4:
+    case 8:
+      palEntry = palette->logpalette.palPalEntry;
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = palEntry[pixel].peBlue;
+	  *bbits++ = palEntry[pixel].peGreen;
+	  *bbits++ = palEntry[pixel].peRed;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    default: /* ? bit bmp -> 24 bit DIB */
+      FIXME(bitmap, "24 bit DIB %d bit bitmap\n",
+	    bmp->bitmap.bmBitsPixel);
+      break;
+    }
+    break;
+    
+
+  case 32: /* 32 bit DIB */
+    switch(bmp->bitmap.bmBitsPixel) {
+      
+    case 24: /* 24/32 bit bmp -> 32 bit DIB */
+    case 32:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = (pixel >>16) & 0xff;
+	  *bbits++ = (pixel >> 8) & 0xff;
+	  *bbits++ =  pixel       & 0xff;
+	  *bbits++ = 0;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+
+    case 15: /* 15/16 bit bmp -> 32 bit DIB */
+    case 16:
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = ((pixel >> 7) & 0xf8) |
+	    ((pixel >> 12) & 0x7);
+	  *bbits++ = ((pixel >> 2) & 0xf8) |
+	    ((pixel >> 7) & 0x7);
+	  *bbits++ = ((pixel << 3) & 0xf8) |
+	    ((pixel >> 2) & 0x7);
+	  *bbits++ = 0;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+      
+    case 1: /* 1/4/8 bit bmp -> 32 bit DIB */
+    case 4:
+    case 8:
+      palEntry = palette->logpalette.palPalEntry;
+      for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
+	for( x = 0; x < xend; x++ ) {
+	  unsigned long pixel=XGetPixel( bmpImage, x, y);
+	  *bbits++ = palEntry[pixel].peBlue;
+	  *bbits++ = palEntry[pixel].peGreen;
+	  *bbits++ = palEntry[pixel].peRed;
+	  *bbits++ = 0;
+	}
+	bbits = (linestart += dstwidth);
+      }
+      break;
+
+    default: /* ? bit bmp -> 32 bit DIB */
+      FIXME(bitmap, "32 bit DIB %d bit bitmap\n",
+	    bmp->bitmap.bmBitsPixel);
+      break;
+    }
+    break;
+
+
+  default: /* ? bit DIB */
+    FIXME(bitmap,"Unsupported DIB depth %d\n",
+	  info->bmiHeader.biBitCount);
+    break;
+  }
+
+  XDestroyImage( bmpImage );
+  LeaveCriticalSection( &X11DRV_CritSection );
+  
+  if(info->bmiHeader.biSizeImage == 0) /* Fill in biSizeImage */
+    info->bmiHeader.biSizeImage = info->bmiHeader.biHeight *
+      DIB_GetDIBWidthBytes( info->bmiHeader.biWidth,
+			    info->bmiHeader.biBitCount );
+
+  if(bbits - (BYTE *)bits > info->bmiHeader.biSizeImage)
+    ERR(bitmap, "Buffer overrun. Please investigate.\n");
+
+  info->bmiHeader.biCompression = 0;
+
+  GDI_HEAP_UNLOCK( dc->w.hPalette );
+  
+  return lines;
+}
+
+/***********************************************************************
+ *           DIB_DoProtectDIBSection
+ */
+static void X11DRV_DIB_DoProtectDIBSection( BITMAPOBJ *bmp, DWORD new_prot )
+{
+    DIBSECTION *dib = bmp->dib;
+    INT effHeight = dib->dsBm.bmHeight >= 0? dib->dsBm.bmHeight
+                                             : -dib->dsBm.bmHeight;
+    INT totalSize = dib->dsBmih.biSizeImage? dib->dsBmih.biSizeImage
+                         : dib->dsBm.bmWidthBytes * effHeight;
+    DWORD old_prot;
+
+    VirtualProtect(dib->dsBm.bmBits, totalSize, new_prot, &old_prot);
+    TRACE(bitmap, "Changed protection from %ld to %ld\n", 
+                  old_prot, new_prot);
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_DoUpdateDIBSection
+ */
+static void X11DRV_DIB_DoUpdateDIBSection(BITMAPOBJ *bmp, BOOL toDIB)
+{
+  X11DRV_DIBSECTION *dib = (X11DRV_DIBSECTION *) bmp->dib;
+  X11DRV_DIB_SETIMAGEBITS_DESCR descr;
+  
+  if (DIB_GetBitmapInfo( &dib->dibSection.dsBmih, &descr.infoWidth, &descr.lines,
+			 &descr.infoBpp, &descr.compression ) == -1)
+    return;
+
+  descr.dc        = NULL;
+  descr.image     = dib->image;
+  descr.colorMap  = dib->colorMap;
+  descr.nColorMap = dib->nColorMap;
+  descr.bits      = dib->dibSection.dsBm.bmBits;
+  descr.depth     = bmp->bitmap.bmBitsPixel;
+  
+  /* Hack for now */
+  descr.drawable  = ((X11DRV_PHYSBITMAP *)bmp->DDBitmap->physBitmap)->pixmap;
+  descr.gc        = BITMAP_GC(bmp);
+  descr.xSrc      = 0;
+  descr.ySrc      = 0;
+  descr.xDest     = 0;
+  descr.yDest     = 0;
+  descr.width     = bmp->bitmap.bmWidth;
+  descr.height    = bmp->bitmap.bmHeight;
+
+  if (toDIB)
+    {
+      TRACE(bitmap, "Copying from Pixmap to DIB bits\n");
+      EnterCriticalSection( &X11DRV_CritSection );
+      CALL_LARGE_STACK( X11DRV_DIB_GetImageBits, &descr );
+      LeaveCriticalSection( &X11DRV_CritSection );
+    }
+  else
+    {
+      TRACE(bitmap, "Copying from DIB bits to Pixmap\n"); 
+      EnterCriticalSection( &X11DRV_CritSection );
+      CALL_LARGE_STACK( X11DRV_DIB_SetImageBits, &descr );
+      LeaveCriticalSection( &X11DRV_CritSection );
+    }
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_FaultHandler
+ */
+static BOOL X11DRV_DIB_FaultHandler( LPVOID res, LPCVOID addr )
+{
+  BOOL handled = FALSE;
+  BITMAPOBJ *bmp;
+  
+  bmp = (BITMAPOBJ *)GDI_GetObjPtr( (HBITMAP)res, BITMAP_MAGIC );
+  if (!bmp) return FALSE;
+  
+  if (bmp->dib)
+    switch (((X11DRV_DIBSECTION *) bmp->dib)->status)
+      {
+      case X11DRV_DIB_GdiMod:
+	TRACE( bitmap, "called in status DIB_GdiMod\n" );
+	X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_READWRITE );
+	X11DRV_DIB_DoUpdateDIBSection( bmp, TRUE );
+	X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
+	((X11DRV_DIBSECTION *) bmp->dib)->status = X11DRV_DIB_InSync;
+	handled = TRUE;
+	break;
+	
+      case X11DRV_DIB_InSync:
+	TRACE( bitmap, "called in status X11DRV_DIB_InSync\n" );
+	X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_READWRITE );
+	((X11DRV_DIBSECTION *) bmp->dib)->status = X11DRV_DIB_AppMod;
+	handled = TRUE;
+	break;
+	
+      case X11DRV_DIB_AppMod:
+	FIXME( bitmap, "called in status X11DRV_DIB_AppMod: "
+	       "this can't happen!\n" );
+	break;
+	
+      case X11DRV_DIB_NoHandler:
+	FIXME( bitmap, "called in status DIB_NoHandler: "
+	       "this can't happen!\n" );
+	break;
+      }
+  
+  GDI_HEAP_UNLOCK( (HBITMAP)res );
+  return handled;
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_UpdateDIBSection
+ */
+void X11DRV_DIB_UpdateDIBSection(DC *dc, BOOL toDIB)
+{
+  BITMAPOBJ *bmp;
+  
+  /* Ensure this is a Compatible DC that has a DIB section selected */
+  
+  if (!dc) return;
+  if (!(dc->w.flags & DC_MEMORY)) return;
+  
+  bmp = (BITMAPOBJ *)GDI_GetObjPtr( dc->w.hBitmap, BITMAP_MAGIC );
+  if (!bmp) return;
+  
+  if (!bmp->dib)
+    {
+      GDI_HEAP_UNLOCK(dc->w.hBitmap);
+      return;
+    }
+  
+  if (!toDIB)
+    {
+      /* Prepare for access to the DIB by GDI functions */
+      
+      switch (((X11DRV_DIBSECTION *) bmp->dib)->status)
+        {
+        default:
+        case X11DRV_DIB_NoHandler:
+	  X11DRV_DIB_DoUpdateDIBSection( bmp, FALSE );
+	  break;
+	  
+        case X11DRV_DIB_GdiMod:
+	  TRACE( bitmap, "fromDIB called in status X11DRV_DIB_GdiMod\n" );
+	  /* nothing to do */
+	  break;
+	  
+        case X11DRV_DIB_InSync:
+	  TRACE( bitmap, "fromDIB called in status X11DRV_DIB_InSync\n" );
+	  /* nothing to do */
+	  break;
+	  
+        case X11DRV_DIB_AppMod:
+	  TRACE( bitmap, "fromDIB called in status X11DRV_DIB_AppMod\n" );
+	  X11DRV_DIB_DoUpdateDIBSection( bmp, FALSE );
+	  X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
+	  ((X11DRV_DIBSECTION *) bmp->dib)->status = X11DRV_DIB_InSync;
+	  break;
+        }
+    }
+  else
+    {
+      /* Acknowledge write access to the DIB by GDI functions */
+      
+      switch (((X11DRV_DIBSECTION *) bmp->dib)->status)
+        {
+        default:
+        case X11DRV_DIB_NoHandler:
+	  X11DRV_DIB_DoUpdateDIBSection( bmp, TRUE );
+	  break;
+	  
+        case X11DRV_DIB_GdiMod:
+	  TRACE( bitmap, "  toDIB called in status X11DRV_DIB_GdiMod\n" );
+	  /* nothing to do */
+	  break;
+	  
+        case X11DRV_DIB_InSync:
+	  TRACE( bitmap, "  toDIB called in status X11DRV_DIB_InSync\n" );
+	  X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_NOACCESS );
+	  ((X11DRV_DIBSECTION *) bmp->dib)->status = X11DRV_DIB_GdiMod;
+	  break;
+	  
+        case X11DRV_DIB_AppMod:
+	  FIXME( bitmap, "  toDIB called in status X11DRV_DIB_AppMod: "
+		 "this can't happen!\n" );
+	  break;
+        }
+    }
+
+    GDI_HEAP_UNLOCK(dc->w.hBitmap);
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_CreateDIBSection16
+ */
+HBITMAP16 X11DRV_DIB_CreateDIBSection16(
+  DC *dc, BITMAPINFO *bmi, UINT16 usage,
+  SEGPTR *bits, HANDLE section,
+  DWORD offset)
+{
+  HBITMAP res = X11DRV_DIB_CreateDIBSection(dc, bmi, usage, NULL, 
+					    section, offset);
+  if ( res )
+    {
+      BITMAPOBJ *bmp = (BITMAPOBJ *) GDI_GetObjPtr(res, BITMAP_MAGIC);
+      if ( bmp && bmp->dib )
+	{
+	  DIBSECTION *dib = bmp->dib;
+	  INT height = dib->dsBm.bmHeight >= 0 ?
+	    dib->dsBm.bmHeight : -dib->dsBm.bmHeight;
+	  INT size = dib->dsBmih.biSizeImage ?
+	    dib->dsBmih.biSizeImage : dib->dsBm.bmWidthBytes * height;
+	  if ( dib->dsBm.bmBits )
+	    {
+	      ((X11DRV_DIBSECTION *) bmp->dib)->selector = 
+		SELECTOR_AllocBlock( dib->dsBm.bmBits, size, 
+				     SEGMENT_DATA, FALSE, FALSE );
+	    }
+	  printf("ptr = %p, size =%d, selector = %04x, segptr = %ld\n",
+		 dib->dsBm.bmBits, size, ((X11DRV_DIBSECTION *) bmp->dib)->selector,
+		 PTR_SEG_OFF_TO_SEGPTR(((X11DRV_DIBSECTION *) bmp->dib)->selector, 0));
+	}
+      GDI_HEAP_UNLOCK( res );
+      
+      if ( bits ) 
+	*bits = PTR_SEG_OFF_TO_SEGPTR( ((X11DRV_DIBSECTION *) bmp->dib)->selector, 0 );
+    }
+
+    return res;
+}
+
+
+/***********************************************************************
+ *           X11DRV_DIB_CreateDIBSection
+ */
+HBITMAP X11DRV_DIB_CreateDIBSection(
+  DC *dc, BITMAPINFO *bmi, UINT usage,
+  LPVOID *bits, HANDLE section,
+  DWORD offset)
+{
+  HBITMAP res = 0;
+  BITMAPOBJ *bmp = NULL;
+  X11DRV_DIBSECTION *dib = NULL;
+  int *colorMap = NULL;
+  int nColorMap;
+  
+  /* Fill BITMAP32 structure with DIB data */
+  BITMAPINFOHEADER *bi = &bmi->bmiHeader;
+  INT effHeight, totalSize;
+  BITMAP bm;
+  
+  TRACE(bitmap, "format (%ld,%ld), planes %d, bpp %d, size %ld, colors %ld (%s)\n",
+	bi->biWidth, bi->biHeight, bi->biPlanes, bi->biBitCount,
+	bi->biSizeImage, bi->biClrUsed, usage == DIB_PAL_COLORS? "PAL" : "RGB");
+  
+  bm.bmType = 0;
+  bm.bmWidth = bi->biWidth;
+  bm.bmHeight = bi->biHeight;
+  bm.bmWidthBytes = DIB_GetDIBWidthBytes(bm.bmWidth, bi->biBitCount);
+  bm.bmPlanes = bi->biPlanes;
+  bm.bmBitsPixel = bi->biBitCount;
+  bm.bmBits = NULL;
+  
+  /* Get storage location for DIB bits */
+  effHeight = bm.bmHeight >= 0 ? bm.bmHeight : -bm.bmHeight;
+  totalSize = bi->biSizeImage? bi->biSizeImage : bm.bmWidthBytes * effHeight;
+  
+  if (section)
+    bm.bmBits = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 
+			      0L, offset, totalSize);
+  else
+    bm.bmBits = VirtualAlloc(NULL, totalSize, 
+			     MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
+  
+  /* Create Color Map */
+  if (bm.bmBits && bm.bmBitsPixel <= 8)
+    {
+      if(dc)
+	colorMap = X11DRV_DIB_BuildColorMap( dc, usage, bm.bmBitsPixel,
+					     bmi, &nColorMap );
+    }
+
+  /* Allocate Memory for DIB and fill structure */
+  if (bm.bmBits)
+    dib = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(X11DRV_DIBSECTION));
+  if (dib)
+    {
+      dib->dibSection.dsBm = bm;
+      dib->dibSection.dsBmih = *bi;
+      /* FIXME: dib->dibSection.dsBitfields ??? */
+      dib->dibSection.dshSection = section;
+      dib->dibSection.dsOffset = offset;
+      
+      dib->status    = X11DRV_DIB_NoHandler;
+      dib->selector  = 0;
+      
+      dib->nColorMap = nColorMap;
+      dib->colorMap  = colorMap;
+    }
+  
+  /* Create Device Dependent Bitmap and add DIB pointer */
+  if (dib) 
+    {
+      res = CreateDIBitmap(dc->hSelf, bi, 0, NULL, bmi, usage);
+      if (res)
+	{
+	  bmp = (BITMAPOBJ *) GDI_GetObjPtr(res, BITMAP_MAGIC);
+	  if (bmp)
+	    {
+	      bmp->dib = (DIBSECTION *) dib;
+	      /* HACK for now */
+	      if(!bmp->DDBitmap)
+		X11DRV_CreateBitmap(res); 
+	    }
+	}
+    }
+  
+  /* Create XImage */
+  if (dib && bmp)
+    XCREATEIMAGE( dib->image, bm.bmWidth, effHeight, bmp->bitmap.bmBitsPixel );
+  
+  /* Clean up in case of errors */
+  if (!res || !bmp || !dib || !bm.bmBits || (bm.bmBitsPixel <= 8 && !colorMap))
+    {
+      TRACE(bitmap, "got an error res=%08x, bmp=%p, dib=%p, bm.bmBits=%p\n",
+	    res, bmp, dib, bm.bmBits);
+      if (bm.bmBits)
+        {
+	  if (section)
+	    UnmapViewOfFile(bm.bmBits), bm.bmBits = NULL;
+	  else
+	    VirtualFree(bm.bmBits, MEM_RELEASE, 0L), bm.bmBits = NULL;
+        }
+      
+      if (dib && dib->image) { XDestroyImage(dib->image); dib->image = NULL; }
+      if (colorMap) { HeapFree(GetProcessHeap(), 0, colorMap); colorMap = NULL; }
+      if (dib) { HeapFree(GetProcessHeap(), 0, dib); dib = NULL; }
+      if (res) { DeleteObject(res); res = 0; }
+    }
+  
+  /* Install fault handler, if possible */
+  if (bm.bmBits)
+    {
+      if (VIRTUAL_SetFaultHandler(bm.bmBits, X11DRV_DIB_FaultHandler, (LPVOID)res))
+        {
+	  X11DRV_DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
+	  if (dib) dib->status = X11DRV_DIB_InSync;
+        }
+    }
+
+  /* Return BITMAP handle and storage location */
+  if (res) GDI_HEAP_UNLOCK(res);
+  if (bm.bmBits && bits) *bits = bm.bmBits;
+  return res;
+}
+
+/***********************************************************************
+ *           X11DRV_DIB_DeleteDIBSection
+ */
+void X11DRV_DIB_DeleteDIBSection(BITMAPOBJ *bmp)
+{
+  X11DRV_DIBSECTION *dib = (X11DRV_DIBSECTION *) bmp->dib;
+
+  if (dib->image) 
+    XDestroyImage( dib->image );
+  
+  if (dib->colorMap)
+    HeapFree(GetProcessHeap(), 0, dib->colorMap);
+  
+  if (dib->selector)
+    {
+      WORD count = (GET_SEL_LIMIT( dib->selector ) >> 16) + 1;
+      SELECTOR_FreeBlock( dib->selector, count );
+    }
+}
+
+
 #endif /* !defined(X_DISPLAY_MISSING) */
+
+
+
diff --git a/graphics/x11drv/graphics.c b/graphics/x11drv/graphics.c
index 531caf9..4c687cc 100644
--- a/graphics/x11drv/graphics.c
+++ b/graphics/x11drv/graphics.c
@@ -96,10 +96,10 @@
 	val.foreground = physDev->brush.pixel;
 	val.background = physDev->backgroundPixel;
     }
-    if (fMapColors && COLOR_PixelToPalette)
+    if (fMapColors && X11DRV_PALETTE_XPixelToPalette)
     {
-        val.foreground = COLOR_PixelToPalette[val.foreground];
-        val.background = COLOR_PixelToPalette[val.background];
+        val.foreground = X11DRV_PALETTE_XPixelToPalette[val.foreground];
+        val.background = X11DRV_PALETTE_XPixelToPalette[val.background];
     }
 
     if (dc->w.flags & DC_DIRTY) CLIPPING_UpdateGCRegion(dc);
@@ -126,7 +126,7 @@
         break;
 
     case FillTiled:
-        if (fMapColors && COLOR_PixelToPalette)
+        if (fMapColors && X11DRV_PALETTE_XPixelToPalette)
         {
             register int x, y;
             XImage *image;
@@ -140,7 +140,7 @@
             for (y = 0; y < 8; y++)
                 for (x = 0; x < 8; x++)
                     XPutPixel( image, x, y,
-                               COLOR_PixelToPalette[XGetPixel( image, x, y)] );
+                               X11DRV_PALETTE_XPixelToPalette[XGetPixel( image, x, y)] );
             XPutImage( display, pixmap, gc, image, 0, 0, 0, 0, 8, 8 );
             XDestroyImage( image );
             LeaveCriticalSection( &X11DRV_CritSection );
@@ -829,7 +829,7 @@
     
     x = dc->w.DCOrgX + XLPTODP( dc, x );
     y = dc->w.DCOrgY + YLPTODP( dc, y );
-    pixel = COLOR_ToPhysical( dc, color );
+    pixel = X11DRV_PALETTE_ToPhysical( dc, color );
     
     TSXSetForeground( display, physDev->gc, pixel );
     TSXSetFunction( display, physDev->gc, GXcopy );
@@ -837,7 +837,7 @@
 
     /* inefficient but simple... */
 
-    return COLOR_ToLogical(pixel);
+    return X11DRV_PALETTE_ToLogical(pixel);
 }
 
 
@@ -874,7 +874,7 @@
     XDestroyImage( image );
     LeaveCriticalSection( &X11DRV_CritSection );
     
-    return COLOR_ToLogical(pixel);
+    return X11DRV_PALETTE_ToLogical(pixel);
 }
 
 
@@ -1171,7 +1171,7 @@
                                  YLPTODP(dc,params->y) + dc->w.DCOrgY - rect.top,
                                  rect.left,
                                  rect.top,
-                                 COLOR_ToPhysical( dc, params->color ),
+                                 X11DRV_PALETTE_ToPhysical( dc, params->color ),
                                  params->fillType );
     }
 
@@ -1416,7 +1416,7 @@
     oldColor = dc->w.backgroundColor;
     dc->w.backgroundColor = color;
 
-    physDev->backgroundPixel = COLOR_ToPhysical( dc, color );
+    physDev->backgroundPixel = X11DRV_PALETTE_ToPhysical( dc, color );
 
     return oldColor;
 }
@@ -1433,7 +1433,7 @@
     oldColor = dc->w.textColor;
     dc->w.textColor = color;
 
-    physDev->textPixel = COLOR_ToPhysical( dc, color );
+    physDev->textPixel = X11DRV_PALETTE_ToPhysical( dc, color );
 
     return oldColor;
 }
diff --git a/graphics/x11drv/init.c b/graphics/x11drv/init.c
index 032a846..dace949 100644
--- a/graphics/x11drv/init.c
+++ b/graphics/x11drv/init.c
@@ -11,14 +11,15 @@
 #include "ts_xlib.h"
 
 #include <string.h>
-#include "x11drv.h"
-#include "color.h"
+
 #include "bitmap.h"
-#include "winnt.h"
-#include "local.h"
+#include "color.h"
 #include "debug.h"
 #include "ldt.h"
+#include "local.h"
 #include "monitor.h"
+#include "winnt.h"
+#include "x11drv.h"
 
 static BOOL X11DRV_CreateDC( DC *dc, LPCSTR driver, LPCSTR device,
                                LPCSTR output, const DEVMODE16* initData );
@@ -36,6 +37,8 @@
     X11DRV_CreateBitmap,             /* pCreateBitmap */
     X11DRV_CreateDC,                 /* pCreateDC */
     X11DRV_DeleteDC,                 /* pDeleteDC */
+    X11DRV_DIB_CreateDIBSection,     /* pCreateDIBSection */
+    X11DRV_DIB_CreateDIBSection16,   /* pCreateDIBSection16 */
     X11DRV_DeleteObject,             /* pDeleteObject */
     X11DRV_Ellipse,                  /* pEllipse */
     X11DRV_EnumDeviceFonts,          /* pEnumDeviceFonts */
@@ -97,7 +100,26 @@
     NULL                             /* pStretchDIBits */
 };
 
-static DeviceCaps X11DRV_DevCaps = {
+GDI_DRIVER X11DRV_GDI_Driver =
+{
+  X11DRV_GDI_Initialize,
+  X11DRV_GDI_Finalize
+};
+
+BITMAP_DRIVER X11DRV_BITMAP_Driver =
+{
+  X11DRV_DIB_SetDIBits,
+  X11DRV_DIB_GetDIBits,
+  X11DRV_DIB_DeleteDIBSection
+};
+
+PALETTE_DRIVER X11DRV_PALETTE_Driver =
+{
+  X11DRV_PALETTE_SetMapping,
+  X11DRV_PALETTE_UpdateMapping
+};
+
+DeviceCaps X11DRV_DevCaps = {
 /* version */		0, 
 /* technology */	DT_RASDISPLAY,
 /* size, resolution */	0, 0, 0, 0, 0, 
@@ -120,15 +142,18 @@
 /* ..etc */		0, 0 };
 
 /**********************************************************************
- *	     X11DRV_Init
+ *	     X11DRV_GDI_Initialize
  */
-BOOL X11DRV_Init(void)
+BOOL X11DRV_GDI_Initialize(void)
 {
+    BITMAP_Driver = &X11DRV_BITMAP_Driver;
+    PALETTE_Driver = &X11DRV_PALETTE_Driver;
+
     /* FIXME: colormap management should be merged with the X11DRV */
 
     if( !X11DRV_DIB_Init() ) return FALSE;
 
-    if( !COLOR_Init() ) return FALSE;
+    if( !X11DRV_PALETTE_Init() ) return FALSE;
 
     if( !X11DRV_OBM_Init() ) return FALSE;
 
@@ -146,14 +171,6 @@
     X11DRV_DevCaps.horzRes = MONITOR_GetWidth(&MONITOR_PrimaryMonitor);
     X11DRV_DevCaps.vertRes = MONITOR_GetHeight(&MONITOR_PrimaryMonitor);
     X11DRV_DevCaps.bitsPixel = MONITOR_GetDepth(&MONITOR_PrimaryMonitor);
-
-    if( COLOR_GetSystemPaletteFlags() & COLOR_VIRTUAL ) 
-	X11DRV_DevCaps.sizePalette = 0;
-    else
-    {
-	X11DRV_DevCaps.rasterCaps |= RC_PALETTE;
-	X11DRV_DevCaps.sizePalette = DefaultVisual(display,DefaultScreen(display))->map_entries;
-    }
  
     /* Resolution will be adjusted during the font init */
 
@@ -176,6 +193,14 @@
 }
 
 /**********************************************************************
+ *	     X11DRV_GDI_Finalize
+ */
+void X11DRV_GDI_Finalize(void)
+{
+  X11DRV_PALETTE_Cleanup();
+}
+
+/**********************************************************************
  *	     X11DRV_CreateDC
  */
 static BOOL X11DRV_CreateDC( DC *dc, LPCSTR driver, LPCSTR device,
diff --git a/graphics/x11drv/oembitmap.c b/graphics/x11drv/oembitmap.c
index 4b9536f..d809515 100644
--- a/graphics/x11drv/oembitmap.c
+++ b/graphics/x11drv/oembitmap.c
@@ -322,10 +322,10 @@
     for (i = 0; i < NB_COLOR_SYMBOLS; i++)
     {
         if (OBM_Colors[i].pixel & 0xff000000)  /* PALETTEINDEX */
-            OBM_Colors[i].pixel = COLOR_ToPhysical( NULL,
+            OBM_Colors[i].pixel = X11DRV_PALETTE_ToPhysical( NULL,
                                     GetSysColor(OBM_Colors[i].pixel & 0xff));
         else  /* RGB*/
-            OBM_Colors[i].pixel = COLOR_ToPhysical( NULL, OBM_Colors[i].pixel);
+            OBM_Colors[i].pixel = X11DRV_PALETTE_ToPhysical( NULL, OBM_Colors[i].pixel);
     }
     return TRUE;
 }
@@ -387,7 +387,7 @@
     attrs = (XpmAttributes *)HEAP_xalloc( GetProcessHeap(), 0,
                                           XpmAttributesSize() );
     attrs->valuemask    = XpmColormap | XpmDepth | XpmColorSymbols |XpmHotspot;
-    attrs->colormap     = X11DRV_COLOR_GetColormap();
+    attrs->colormap     = X11DRV_PALETTE_PaletteXColormap;
     attrs->depth        = descr->color ? MONITOR_GetDepth(&MONITOR_PrimaryMonitor) : 1;
     attrs->colorsymbols = (attrs->depth > 1) ? OBM_Colors : OBM_BlackAndWhite;
     attrs->numsymbols   = (attrs->depth > 1) ? NB_COLOR_SYMBOLS : 2;
@@ -543,7 +543,7 @@
         {
 	    X11DRV_PHYSBITMAP *pbitmapXor = bmpXor->DDBitmap->physBitmap;
             TSXSetForeground( display, BITMAP_colorGC,
-                            COLOR_ToPhysical( NULL, RGB(0,0,0) ));
+                            X11DRV_PALETTE_ToPhysical( NULL, RGB(0,0,0) ));
             TSXSetBackground( display, BITMAP_colorGC, 0 );
             TSXSetFunction( display, BITMAP_colorGC, GXor );
             TSXCopyPlane(display, pbitmapAnd->pixmap, pbitmapXor->pixmap, BITMAP_colorGC,
diff --git a/graphics/x11drv/palette.c b/graphics/x11drv/palette.c
new file mode 100644
index 0000000..959f323
--- /dev/null
+++ b/graphics/x11drv/palette.c
@@ -0,0 +1,979 @@
+/* 
+ * X11DRV OEM bitmap objects
+ *
+ * Copyright 1994, 1995 Alexandre Julliard
+ *
+ */
+
+#include "config.h"
+
+#ifndef X_DISPLAY_MISSING
+
+#include "ts_xlib.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "color.h"
+#include "debug.h"
+#include "gdi.h"
+#include "monitor.h"
+#include "options.h"
+#include "palette.h"
+#include "windef.h"
+#include "xmalloc.h"
+#include "x11drv.h"
+
+/* Palette indexed mode:
+ *	logical palette -> mapping -> pixel
+ *				     
+ *
+ * Windows needs contiguous color space ( from 0 to n ) but 
+ * it is possible only with the private colormap. Otherwise we
+ * have to map DC palette indices to real pixel values. With 
+ * private colormaps it boils down to the identity mapping. The
+ * other special case is when we have a fixed color visual with 
+ * the screendepth > 8 - we abandon palette mappings altogether 
+ * because pixel values can be calculated without X server 
+ * assistance.
+ *
+ * Windows palette manager is described in the
+ * http://premium.microsoft.com/msdn/library/techart/f30/f34/f40/d4d/sa942.htm
+ */
+
+extern PALETTEENTRY *COLOR_sysPal;
+extern int COLOR_gapStart;
+extern int COLOR_gapEnd;
+extern int COLOR_gapFilled;
+extern int COLOR_max;
+
+extern const PALETTEENTRY COLOR_sysPalTemplate[NB_RESERVED_COLORS]; 
+
+Colormap X11DRV_PALETTE_PaletteXColormap = 0;
+UINT16   X11DRV_PALETTE_PaletteFlags     = 0;
+
+static int X11DRV_PALETTE_Redshift   = 0; /* to handle abortive X11DRV_PALETTE_VIRTUAL visuals */
+static int X11DRV_PALETTE_Redmax     = 0;
+static int X11DRV_PALETTE_Greenshift = 0;
+static int X11DRV_PALETTE_Greenmax   = 0;
+static int X11DRV_PALETTE_Blueshift  = 0;
+static int X11DRV_PALETTE_Bluemax    = 0;
+static int X11DRV_PALETTE_Graymax    = 0;
+
+/* First free dynamic color cell, 0 = full palette, -1 = fixed palette */
+static int           X11DRV_PALETTE_firstFree = 0; 
+static unsigned char X11DRV_PALETTE_freeList[256];
+
+/**********************************************************************/
+
+   /* Map an EGA index (0..15) to a pixel value in the system color space.  */
+
+int X11DRV_PALETTE_mapEGAPixel[16];
+
+/**********************************************************************/
+
+#define NB_COLORCUBE_START_INDEX	63
+
+/* Maps entry in the system palette to X pixel value */
+int *X11DRV_PALETTE_PaletteToXPixel = NULL;
+
+/* Maps pixel to the entry in the system palette */
+int *X11DRV_PALETTE_XPixelToPalette = NULL;
+
+/**********************************************************************/
+
+static BOOL X11DRV_PALETTE_BuildPrivateMap(void);
+static BOOL X11DRV_PALETTE_BuildSharedMap(void);
+static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, int *shift, int *max);
+static void X11DRV_PALETTE_FillDefaultColors(void);
+static void X11DRV_PALETTE_FormatSystemPalette(void);
+static BOOL X11DRV_PALETTE_CheckSysColor(COLORREF c);
+
+/***********************************************************************
+ *           COLOR_Init
+ *
+ * Initialize color management.
+ */
+BOOL X11DRV_PALETTE_Init(void)
+{
+    int	mask, white, black;
+    int monoPlane;
+
+    Visual *visual = DefaultVisual( display, DefaultScreen(display) );
+
+    TRACE(palette, "initializing palette manager...\n");
+
+    white = WhitePixelOfScreen( X11DRV_GetXScreen() );
+    black = BlackPixelOfScreen( X11DRV_GetXScreen() );
+    monoPlane = 1;
+    for( mask = 1; !((white & mask)^(black & mask)); mask <<= 1 )
+	 monoPlane++;
+    X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
+    X11DRV_DevCaps.sizePalette = visual->map_entries;
+
+    switch(visual->class)
+    {
+    case DirectColor:
+	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
+    case GrayScale:
+    case PseudoColor:
+	if (Options.usePrivateMap)
+	{
+	    XSetWindowAttributes win_attr;
+
+	    X11DRV_PALETTE_PaletteXColormap = TSXCreateColormap( display, X11DRV_GetXRootWindow(),
+						 visual, AllocAll );
+	    if (X11DRV_PALETTE_PaletteXColormap)
+	    {
+	        X11DRV_PALETTE_PaletteFlags |= (X11DRV_PALETTE_PRIVATE | X11DRV_PALETTE_WHITESET);
+
+		monoPlane = 1;
+		for( white = X11DRV_DevCaps.sizePalette - 1; !(white & 1); white >>= 1 )
+		     monoPlane++;
+
+	        if( X11DRV_GetXRootWindow() != DefaultRootWindow(display) )
+	        {
+		    win_attr.colormap = X11DRV_PALETTE_PaletteXColormap;
+		    TSXChangeWindowAttributes( display, X11DRV_GetXRootWindow(),
+					 CWColormap, &win_attr );
+		}
+		break;
+	    }
+	}
+	X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
+        break;
+
+    case StaticGray:
+	X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
+	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
+        X11DRV_PALETTE_Graymax = (1<<MONITOR_GetDepth(&MONITOR_PrimaryMonitor))-1;
+        break;
+
+    case TrueColor:
+	X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_VIRTUAL;
+    case StaticColor: {
+    	int *depths,nrofdepths;
+	/* FIXME: hack to detect XFree32 XF_VGA16 ... We just have
+	 * depths 1 and 4
+	 */
+	depths=TSXListDepths(display,DefaultScreen(display),&nrofdepths);
+	if ((nrofdepths==2) && ((depths[0]==4) || depths[1]==4)) {
+	    monoPlane = 1;
+	    for( white = X11DRV_DevCaps.sizePalette - 1; !(white & 1); white >>= 1 )
+	        monoPlane++;
+    	    X11DRV_PALETTE_PaletteFlags = (white & mask) ? X11DRV_PALETTE_WHITESET : 0;
+	    X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
+	    TSXFree(depths);
+	    break;
+	}
+	TSXFree(depths);
+        X11DRV_PALETTE_PaletteXColormap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
+        X11DRV_PALETTE_PaletteFlags |= X11DRV_PALETTE_FIXED;
+        X11DRV_PALETTE_ComputeShifts(visual->red_mask, &X11DRV_PALETTE_Redshift, &X11DRV_PALETTE_Redmax);
+	X11DRV_PALETTE_ComputeShifts(visual->green_mask, &X11DRV_PALETTE_Greenshift, &X11DRV_PALETTE_Greenmax);
+        X11DRV_PALETTE_ComputeShifts(visual->blue_mask, &X11DRV_PALETTE_Blueshift, &X11DRV_PALETTE_Bluemax);
+	break;
+    }
+    }
+
+    TRACE(palette," visual class %i (%i)\n",  visual->class, monoPlane);
+
+    memset(X11DRV_PALETTE_freeList, 0, 256*sizeof(unsigned char));
+
+    if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
+        X11DRV_PALETTE_BuildPrivateMap();
+    else
+        X11DRV_PALETTE_BuildSharedMap();
+
+    /* Build free list */
+
+    if( X11DRV_PALETTE_firstFree != -1 )
+        X11DRV_PALETTE_FormatSystemPalette();
+
+    X11DRV_PALETTE_FillDefaultColors();
+
+    if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
+	X11DRV_DevCaps.sizePalette = 0;
+    else
+    {
+	X11DRV_DevCaps.rasterCaps |= RC_PALETTE;
+	X11DRV_DevCaps.sizePalette = visual->map_entries;
+    }
+
+    return TRUE;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_Cleanup
+ *
+ * Free external colors we grabbed in the FillDefaultPalette()
+ */
+void X11DRV_PALETTE_Cleanup(void)
+{
+  if( COLOR_gapFilled )
+    TSXFreeColors(display, X11DRV_PALETTE_PaletteXColormap, 
+		  (unsigned long*)(X11DRV_PALETTE_PaletteToXPixel + COLOR_gapStart), 
+		  COLOR_gapFilled, 0);
+}
+
+/***********************************************************************
+ *		X11DRV_PALETTE_ComputeShifts
+ *
+ * Calculate conversion parameters for direct mapped visuals
+ */
+static void X11DRV_PALETTE_ComputeShifts(unsigned long maskbits, int *shift, int *max)
+{
+    int i;
+
+    if (maskbits==0)
+    {
+        *shift=0;
+        *max=0;
+        return;
+    }
+
+    for(i=0;!(maskbits&1);i++)
+        maskbits >>= 1;
+
+    *shift = i;
+    *max = maskbits;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_BuildPrivateMap
+ *
+ * Allocate colorcells and initialize mapping tables.
+ */
+static BOOL X11DRV_PALETTE_BuildPrivateMap(void)
+{
+    /* Private colormap - identity mapping */
+
+    XColor color;
+    int i; 
+
+    COLOR_sysPal = (PALETTEENTRY*)xmalloc(sizeof(PALETTEENTRY)*X11DRV_DevCaps.sizePalette);
+
+    TRACE(palette,"Building private map - %i palette entries\n", X11DRV_DevCaps.sizePalette);
+
+      /* Allocate system palette colors */ 
+
+    for( i=0; i < X11DRV_DevCaps.sizePalette; i++ )
+    {
+       if( i < NB_RESERVED_COLORS/2 )
+       {
+         color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
+         color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
+         color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
+	 COLOR_sysPal[i] = COLOR_sysPalTemplate[i];
+       }
+       else if( i >= X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS/2 )
+       {
+	 int j = NB_RESERVED_COLORS + i - X11DRV_DevCaps.sizePalette;
+         color.red   = COLOR_sysPalTemplate[j].peRed * 65535 / 255;
+         color.green = COLOR_sysPalTemplate[j].peGreen * 65535 / 255;
+         color.blue  = COLOR_sysPalTemplate[j].peBlue * 65535 / 255;
+	 COLOR_sysPal[i] = COLOR_sysPalTemplate[j];
+       }
+
+       color.flags = DoRed | DoGreen | DoBlue;
+       color.pixel = i;
+       TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
+
+       /* Set EGA mapping if color is from the first or last eight */
+
+       if (i < 8)
+           X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
+       else if (i >= X11DRV_DevCaps.sizePalette - 8 )
+           X11DRV_PALETTE_mapEGAPixel[i - (X11DRV_DevCaps.sizePalette - 16)] = color.pixel;
+    }
+
+    X11DRV_PALETTE_XPixelToPalette = X11DRV_PALETTE_PaletteToXPixel = NULL;
+
+    COLOR_gapStart = 256; COLOR_gapEnd = -1;
+
+    X11DRV_PALETTE_firstFree = (X11DRV_DevCaps.sizePalette > NB_RESERVED_COLORS)?NB_RESERVED_COLORS/2 : -1;
+
+    return FALSE;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_BuildSharedMap
+ *
+ * Allocate colorcells and initialize mapping tables.
+ */
+static BOOL X11DRV_PALETTE_BuildSharedMap(void)
+{
+   XColor		color;
+   unsigned long        sysPixel[NB_RESERVED_COLORS];
+   unsigned long*	pixDynMapping = NULL;
+   unsigned long	plane_masks[1];
+   int			i, j, warn = 0;
+   int			diff, r, g, b, max = 256, bp = 0, wp = 1;
+   int			step = 1;
+
+   /* read "AllocSystemColors" from wine.conf */
+
+   COLOR_max = PROFILE_GetWineIniInt( "options", "AllocSystemColors", 256);
+   if (COLOR_max > 256) COLOR_max = 256;
+   else if (COLOR_max < 20) COLOR_max = 20;
+   TRACE(palette,"%d colors configured.\n", COLOR_max);
+   
+   TRACE(palette,"Building shared map - %i palette entries\n", X11DRV_DevCaps.sizePalette);
+
+   /* Be nice and allocate system colors as read-only */
+
+   for( i = 0; i < NB_RESERVED_COLORS; i++ )
+     { 
+        color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
+        color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
+        color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
+        color.flags = DoRed | DoGreen | DoBlue;
+
+        if (!TSXAllocColor( display, X11DRV_PALETTE_PaletteXColormap, &color ))
+        { 
+	     XColor	best, c;
+	     
+             if( !warn++ ) 
+	     {
+		  WARN(palette, "Not enough colors for the full system palette.\n");
+
+	          bp = BlackPixel(display, DefaultScreen(display));
+	          wp = WhitePixel(display, DefaultScreen(display));
+
+	          max = (0xffffffff)>>(32 - MONITOR_GetDepth(&MONITOR_PrimaryMonitor));
+	          if( max > 256 ) 
+	          {
+	  	      step = max/256;
+		      max = 256;
+	          }
+	     }
+
+	     /* reinit color (XAllocColor() may change it)
+	      * and map to the best shared colorcell */
+
+             color.red   = COLOR_sysPalTemplate[i].peRed * 65535 / 255;
+             color.green = COLOR_sysPalTemplate[i].peGreen * 65535 / 255;
+             color.blue  = COLOR_sysPalTemplate[i].peBlue * 65535 / 255;
+
+	     best.pixel = best.red = best.green = best.blue = 0;
+	     for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
+	     {
+		TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &c);
+		r = (c.red - color.red)>>8; 
+		g = (c.green - color.green)>>8; 
+		b = (c.blue - color.blue)>>8;
+		r = r*r + g*g + b*b;
+		if( r < diff ) { best = c; diff = r; }
+	     }
+
+	     if( TSXAllocColor(display, X11DRV_PALETTE_PaletteXColormap, &best) )
+		 color.pixel = best.pixel;
+	     else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
+        }
+
+        sysPixel[i] = color.pixel;
+
+        TRACE(palette,"syscolor(%lx) -> pixel %i\n",
+		      *(COLORREF*)(COLOR_sysPalTemplate+i), (int)color.pixel);
+
+        /* Set EGA mapping if color in the first or last eight */
+
+        if (i < 8)
+            X11DRV_PALETTE_mapEGAPixel[i] = color.pixel;
+        else if (i >= NB_RESERVED_COLORS - 8 )
+            X11DRV_PALETTE_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
+     }
+
+   /* now allocate changeable set */
+
+   if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )  
+     {
+	int c_min = 0, c_max = X11DRV_DevCaps.sizePalette, c_val;
+
+	TRACE(palette,"Dynamic colormap... \n");
+
+	/* comment this out if you want to debug palette init */
+
+	TSXGrabServer(display);
+
+	/* let's become the first client that actually follows 
+	 * X guidelines and does binary search...
+	 */
+
+	pixDynMapping = (unsigned long*)xmalloc(sizeof(long)*X11DRV_DevCaps.sizePalette);
+        while( c_max - c_min > 0 )
+          {
+             c_val = (c_max + c_min)/2 + (c_max + c_min)%2;
+
+             if( !TSXAllocColorCells(display, X11DRV_PALETTE_PaletteXColormap, False,
+                                   plane_masks, 0, pixDynMapping, c_val) )
+                 c_max = c_val - 1;
+             else
+               {
+                 TSXFreeColors(display, X11DRV_PALETTE_PaletteXColormap, pixDynMapping, c_val, 0);
+                 c_min = c_val;
+               }
+          }
+
+	if( c_min > COLOR_max - NB_RESERVED_COLORS) 
+	    c_min = COLOR_max - NB_RESERVED_COLORS;
+
+	c_min = (c_min/2) + (c_min/2);		/* need even set for split palette */
+
+	if( c_min > 0 )
+	  if( !TSXAllocColorCells(display, X11DRV_PALETTE_PaletteXColormap, False,
+                                plane_masks, 0, pixDynMapping, c_min) )
+	    {
+	      WARN(palette,"Inexplicable failure during colorcell allocation.\n");
+	      c_min = 0;
+	    }
+
+        X11DRV_DevCaps.sizePalette = c_min + NB_RESERVED_COLORS;
+
+	TSXUngrabServer(display);
+
+	TRACE(palette,"adjusted size %i colorcells\n", X11DRV_DevCaps.sizePalette);
+     }
+   else if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
+	{
+          /* virtual colorspace - ToPhysical takes care of 
+           * color translations but we have to allocate full palette 
+	   * to maintain compatibility
+	   */
+	  X11DRV_DevCaps.sizePalette = 256;
+	  TRACE(palette,"Virtual colorspace - screendepth %i\n", MONITOR_GetDepth(&MONITOR_PrimaryMonitor));
+	}
+   else X11DRV_DevCaps.sizePalette = NB_RESERVED_COLORS;	/* system palette only - however we can alloc a bunch
+			                 * of colors and map to them */
+
+   TRACE(palette,"Shared system palette uses %i colors.\n", X11DRV_DevCaps.sizePalette);
+
+   /* set gap to account for pixel shortage. It has to be right in the center
+    * of the system palette because otherwise raster ops get screwed. */
+
+   if( X11DRV_DevCaps.sizePalette >= 256 )
+     { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
+   else
+     { COLOR_gapStart = X11DRV_DevCaps.sizePalette/2; COLOR_gapEnd = 255 - X11DRV_DevCaps.sizePalette/2; }
+
+   X11DRV_PALETTE_firstFree = ( X11DRV_DevCaps.sizePalette > NB_RESERVED_COLORS && 
+		      (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL || !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED)) ) 
+		     ? NB_RESERVED_COLORS/2 : -1;
+
+   COLOR_sysPal = (PALETTEENTRY*)xmalloc(sizeof(PALETTEENTRY)*256);
+
+   /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */
+
+   if( MONITOR_GetDepth(&MONITOR_PrimaryMonitor) <= 8 )
+     {
+       X11DRV_PALETTE_XPixelToPalette = (int*)xmalloc(sizeof(int)*256);
+       memset( X11DRV_PALETTE_XPixelToPalette, 0, 256*sizeof(int) );
+     }
+
+   /* for hicolor visuals PaletteToPixel mapping is used to skip
+    * RGB->pixel calculation in X11DRV_PALETTE_ToPhysical(). 
+    */
+
+   X11DRV_PALETTE_PaletteToXPixel = (int*)xmalloc(sizeof(int)*256);
+
+   for( i = j = 0; i < 256; i++ )
+   {
+      if( i >= COLOR_gapStart && i <= COLOR_gapEnd ) 
+      {
+         X11DRV_PALETTE_PaletteToXPixel[i] = 0;
+         COLOR_sysPal[i].peFlags = 0;	/* mark as unused */
+         continue;
+      }
+
+      if( i < NB_RESERVED_COLORS/2 )
+      {
+        X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[i];
+        COLOR_sysPal[i] = COLOR_sysPalTemplate[i];
+      }
+      else if( i >= 256 - NB_RESERVED_COLORS/2 )
+      {
+        X11DRV_PALETTE_PaletteToXPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256]; 
+        COLOR_sysPal[i] = COLOR_sysPalTemplate[(i + NB_RESERVED_COLORS) - 256];
+      }
+      else if( pixDynMapping )
+             X11DRV_PALETTE_PaletteToXPixel[i] = pixDynMapping[j++];
+           else
+             X11DRV_PALETTE_PaletteToXPixel[i] = i;
+
+      TRACE(palette,"index %i -> pixel %i\n", i, X11DRV_PALETTE_PaletteToXPixel[i]);
+
+      if( X11DRV_PALETTE_XPixelToPalette )
+          X11DRV_PALETTE_XPixelToPalette[X11DRV_PALETTE_PaletteToXPixel[i]] = i;
+   }
+
+   if( pixDynMapping ) free(pixDynMapping);
+
+   return TRUE;
+}
+
+/***********************************************************************
+ *      Colormap Initialization
+ */
+static void X11DRV_PALETTE_FillDefaultColors(void)
+{
+ /* initialize unused entries to what Windows uses as a color 
+  * cube - based on Greg Kreider's code. 
+  */
+
+  int i = 0, idx = 0;
+  int red, no_r, inc_r;
+  int green, no_g, inc_g; 
+  int blue, no_b, inc_b;
+  
+  if (X11DRV_DevCaps.sizePalette <= NB_RESERVED_COLORS)
+  	return;
+  while (i*i*i < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) i++;
+  no_r = no_g = no_b = --i;
+  if ((no_r * (no_g+1) * no_b) < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) no_g++;
+  if ((no_r * no_g * (no_b+1)) < (X11DRV_DevCaps.sizePalette - NB_RESERVED_COLORS)) no_b++;
+  inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
+  inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
+  inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;
+
+  idx = X11DRV_PALETTE_firstFree;
+
+  if( idx != -1 )
+    for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
+     for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
+      for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
+      {
+	 /* weird but true */
+
+	 if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;
+
+         COLOR_sysPal[idx].peRed = red;
+         COLOR_sysPal[idx].peGreen = green;
+         COLOR_sysPal[idx].peBlue = blue;
+         
+	 /* set X color */
+
+	 if( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL )
+	 {
+            if (X11DRV_PALETTE_Redmax != 255) no_r = (red * X11DRV_PALETTE_Redmax) / 255;
+            if (X11DRV_PALETTE_Greenmax != 255) no_g = (green * X11DRV_PALETTE_Greenmax) / 255;
+            if (X11DRV_PALETTE_Bluemax != 255) no_b = (blue * X11DRV_PALETTE_Bluemax) / 255;
+
+            X11DRV_PALETTE_PaletteToXPixel[idx] = (no_r << X11DRV_PALETTE_Redshift) | (no_g << X11DRV_PALETTE_Greenshift) | (no_b << X11DRV_PALETTE_Blueshift);
+	 }
+	 else if( !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
+	 {
+	   XColor color = { color.pixel = (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[idx] : idx ,
+	                    COLOR_sysPal[idx].peRed << 8,
+			    COLOR_sysPal[idx].peGreen << 8,
+			    COLOR_sysPal[idx].peGreen << 8,
+			    (DoRed | DoGreen | DoBlue) };
+	   TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
+	 }
+	 idx = X11DRV_PALETTE_freeList[idx];
+      }
+
+  /* try to fill some entries in the "gap" with
+   * what's already in the colormap - they will be
+   * mappable to but not changeable. */
+
+  if( COLOR_gapStart < COLOR_gapEnd && X11DRV_PALETTE_XPixelToPalette )
+  {
+    XColor	xc;
+    int		r, g, b, max;
+
+    max = COLOR_max - (256 - (COLOR_gapEnd - COLOR_gapStart));
+    for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
+      if( X11DRV_PALETTE_XPixelToPalette[i] == 0 )
+	{
+	  xc.pixel = i;
+
+	  TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &xc);
+	  r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;
+
+	  if( xc.pixel < 256 && X11DRV_PALETTE_CheckSysColor(RGB(r, g, b)) &&
+	      TSXAllocColor(display, X11DRV_PALETTE_PaletteXColormap, &xc) )
+	  {
+	     X11DRV_PALETTE_XPixelToPalette[xc.pixel] = idx;
+	     X11DRV_PALETTE_PaletteToXPixel[idx] = xc.pixel;
+           *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
+	     COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
+	     if( --max <= 0 ) break;
+	  }
+	}
+    COLOR_gapFilled = idx - COLOR_gapStart;    
+  }
+}
+
+
+/***********************************************************************
+ *           X11DRV_PALETTE_ToLogical
+ *
+ * Return RGB color for given X pixel.
+ */
+COLORREF X11DRV_PALETTE_ToLogical(int pixel)
+{
+    XColor color;
+
+#if 0
+    /* truecolor visual */
+
+    if (MONITOR_GetDepth(&MONITOR_PrimaryMonitor) >= 24) return pixel;
+#endif
+
+    /* check for hicolor visuals first */
+
+    if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED && !X11DRV_PALETTE_Graymax )
+    {
+         color.red = (pixel >> X11DRV_PALETTE_Redshift) & X11DRV_PALETTE_Redmax;
+         color.green = (pixel >> X11DRV_PALETTE_Greenshift) & X11DRV_PALETTE_Greenmax;
+         color.blue = (pixel >> X11DRV_PALETTE_Blueshift) & X11DRV_PALETTE_Bluemax;
+         return RGB((color.red * 255)/X11DRV_PALETTE_Redmax,
+                    (color.green * 255)/X11DRV_PALETTE_Greenmax,
+                    (color.blue * 255)/X11DRV_PALETTE_Bluemax);
+    }
+
+    /* check if we can bypass X */
+
+    if ((MONITOR_GetDepth(&MONITOR_PrimaryMonitor) <= 8) && (pixel < 256) && 
+       !(X11DRV_PALETTE_PaletteFlags & (X11DRV_PALETTE_VIRTUAL | X11DRV_PALETTE_FIXED)) )
+         return  ( *(COLORREF*)(COLOR_sysPal + 
+		   ((X11DRV_PALETTE_XPixelToPalette)?X11DRV_PALETTE_XPixelToPalette[pixel]:pixel)) ) & 0x00ffffff;
+
+    color.pixel = pixel;
+    TSXQueryColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
+    return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_ToPhysical
+ *
+ * Return the physical color closest to 'color'.
+ */
+int X11DRV_PALETTE_ToPhysical( DC *dc, COLORREF color )
+{
+    WORD 		 index = 0;
+    HPALETTE16		 hPal = (dc)? dc->w.hPalette: STOCK_DEFAULT_PALETTE;
+    unsigned char	 spec_type = color >> 24;
+    PALETTEOBJ* 	 palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
+
+    if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED )
+    {
+        /* there is no colormap limitation; we are going to have to compute
+         * the pixel value from the visual information stored earlier 
+	 */
+
+	unsigned 	long red, green, blue;
+	unsigned 	idx = 0;
+
+	switch(spec_type)
+        {
+          case 2: /* PALETTERGB - not sure if we really need to search palette */
+	
+	    idx = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry,
+					    palPtr->logpalette.palNumEntries,
+					    NULL, color, FALSE);
+
+            if( palPtr->mapping )
+	    {
+	        GDI_HEAP_UNLOCK( hPal );
+		return palPtr->mapping[idx];
+	    }
+
+	    color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
+	    break;
+
+          case 1: /* PALETTEINDEX */
+
+            if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
+            {
+                WARN(palette, "RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
+		GDI_HEAP_UNLOCK( hPal );
+                return 0;
+            }
+
+            if( palPtr->mapping ) 
+	    {
+		GDI_HEAP_UNLOCK( hPal );
+		return palPtr->mapping[idx];
+	    }
+	    color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
+	    break;
+
+	  default:
+	    color &= 0xffffff;
+	    /* fall through to RGB */
+
+	  case 0: /* RGB */
+	    if( dc && (dc->w.bitsPerPixel == 1) )
+	    {
+		GDI_HEAP_UNLOCK( hPal );
+		return (((color >> 16) & 0xff) +
+			((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
+	    }
+
+	}
+
+        red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);
+
+	if (X11DRV_PALETTE_Graymax)
+        {
+	    /* grayscale only; return scaled value */
+	    GDI_HEAP_UNLOCK( hPal );
+            return ( (red * 30 + green * 69 + blue * 11) * X11DRV_PALETTE_Graymax) / 25500;
+	}
+	else
+        {
+	    /* scale each individually and construct the TrueColor pixel value */
+	    if (X11DRV_PALETTE_Redmax != 255) red = (red * X11DRV_PALETTE_Redmax) / 255;
+            if (X11DRV_PALETTE_Greenmax != 255) green = (green * X11DRV_PALETTE_Greenmax) / 255;
+	    if (X11DRV_PALETTE_Bluemax != 255) blue = (blue * X11DRV_PALETTE_Bluemax) / 255;
+
+	    GDI_HEAP_UNLOCK( hPal );
+	    return (red << X11DRV_PALETTE_Redshift) | (green << X11DRV_PALETTE_Greenshift) | (blue << X11DRV_PALETTE_Blueshift);
+        }
+    }
+    else 
+    {
+
+	/* palPtr can be NULL when DC is being destroyed */
+
+	if( !palPtr ) return 0;
+	else if( !palPtr->mapping ) 
+            WARN(palette, "Palette %04x is not realized\n", dc->w.hPalette);
+
+	switch(spec_type)	/* we have to peruse DC and system palette */
+    	{
+	    default:
+		color &= 0xffffff;
+		/* fall through to RGB */
+
+       	    case 0:  /* RGB */
+		if( dc && (dc->w.bitsPerPixel == 1) )
+		{
+		    GDI_HEAP_UNLOCK( hPal );
+		    return (((color >> 16) & 0xff) +
+			    ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
+		}
+
+	    	index = COLOR_PaletteLookupPixel( COLOR_sysPal, 256, 
+						  X11DRV_PALETTE_PaletteToXPixel, color, FALSE);
+
+		/* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
+		 */
+	    	break;
+       	    case 1:  /* PALETTEINDEX */
+		index = color & 0xffff;
+
+	        if( index >= palPtr->logpalette.palNumEntries )
+		    WARN(palette, "RGB(%lx) : index %i is out of bounds\n", color, index); 
+		else if( palPtr->mapping ) index = palPtr->mapping[index];
+
+		/*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
+		 */
+		break;
+            case 2:  /* PALETTERGB */
+		index = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry, 
+                                             palPtr->logpalette.palNumEntries,
+                                             palPtr->mapping, color, FALSE);
+		/* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
+		 */
+		break;
+	}
+    }
+
+    GDI_HEAP_UNLOCK( hPal );
+    return index;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_LookupSystemXPixel
+ */
+int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col)
+{
+ int            i, best = 0, diff = 0x7fffffff;
+ int            size = X11DRV_DevCaps.sizePalette;
+ int            r,g,b;
+
+ for( i = 0; i < size && diff ; i++ )
+    {
+      if( i == NB_RESERVED_COLORS/2 )
+      {
+      	int newi = size - NB_RESERVED_COLORS/2;
+	if (newi>i) i=newi;
+      }
+
+      r = COLOR_sysPal[i].peRed - GetRValue(col);
+      g = COLOR_sysPal[i].peGreen - GetGValue(col);
+      b = COLOR_sysPal[i].peBlue - GetBValue(col);
+
+      r = r*r + g*g + b*b;
+
+      if( r < diff ) { best = i; diff = r; }
+    }
+ 
+ return (X11DRV_PALETTE_PaletteToXPixel)? X11DRV_PALETTE_PaletteToXPixel[best] : best;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_FormatSystemPalette
+ */
+static void X11DRV_PALETTE_FormatSystemPalette(void)
+{
+ /* Build free list so we'd have an easy way to find
+  * out if there are any available colorcells. 
+  */
+
+  int i, j = X11DRV_PALETTE_firstFree = NB_RESERVED_COLORS/2;
+
+  COLOR_sysPal[j].peFlags = 0;
+  for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
+    if( i < COLOR_gapStart || i > COLOR_gapEnd )
+      {
+	COLOR_sysPal[i].peFlags = 0;  /* unused tag */
+	X11DRV_PALETTE_freeList[j] = i;	  /* next */
+        j = i;
+      }
+  X11DRV_PALETTE_freeList[j] = 0;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_CheckSysColor
+ */
+static BOOL X11DRV_PALETTE_CheckSysColor(COLORREF c)
+{
+  int i;
+  for( i = 0; i < NB_RESERVED_COLORS; i++ )
+       if( c == (*(COLORREF*)(COLOR_sysPalTemplate + i) & 0x00ffffff) )
+	   return 0;
+  return 1;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_SetMapping
+ *
+ * Set the color-mapping table for selected palette. 
+ * Return number of entries which mapping has changed.
+ */
+int X11DRV_PALETTE_SetMapping( PALETTEOBJ* palPtr, UINT uStart, UINT uNum, BOOL mapOnly )
+{
+    char flag;
+    int  prevMapping = (palPtr->mapping) ? 1 : 0;
+    int  index, iRemapped = 0;
+
+    /* reset dynamic system palette entries */
+
+    if( !mapOnly && X11DRV_PALETTE_firstFree != -1)
+         X11DRV_PALETTE_FormatSystemPalette();
+
+    /* initialize palette mapping table */
+ 
+    palPtr->mapping = (int*)xrealloc(palPtr->mapping, sizeof(int)*
+                                     palPtr->logpalette.palNumEntries);
+
+    for( uNum += uStart; uStart < uNum; uStart++ )
+    {
+        index = -1;
+        flag = PC_SYS_USED;
+
+        switch( palPtr->logpalette.palPalEntry[uStart].peFlags & 0x07 )
+        {
+	case PC_EXPLICIT:   /* palette entries are indices into system palette */
+            index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
+            if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) ) 
+            {
+                WARN(palette,"PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index); 
+                index = 0;
+            }
+            break;
+
+	case PC_RESERVED:   /* forbid future mappings to this entry */
+            flag |= PC_SYS_RESERVED;
+
+            /* fall through */
+	default:	    /* try to collapse identical colors */
+            index = COLOR_PaletteLookupExactIndex(COLOR_sysPal, 256,  
+                             *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
+            /* fall through */
+	case PC_NOCOLLAPSE: 
+            if( index < 0 )
+            {
+                if( X11DRV_PALETTE_firstFree > 0 && !(X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_FIXED) )
+                {
+                    XColor color;
+                    index = X11DRV_PALETTE_firstFree;  /* ought to be available */
+                    X11DRV_PALETTE_firstFree = X11DRV_PALETTE_freeList[index];
+
+                    color.pixel = (X11DRV_PALETTE_PaletteToXPixel) ? X11DRV_PALETTE_PaletteToXPixel[index] : index;
+                    color.red = palPtr->logpalette.palPalEntry[uStart].peRed << 8;
+                    color.green = palPtr->logpalette.palPalEntry[uStart].peGreen << 8;
+                    color.blue = palPtr->logpalette.palPalEntry[uStart].peBlue << 8;
+                    color.flags = DoRed | DoGreen | DoBlue;
+                    TSXStoreColor(display, X11DRV_PALETTE_PaletteXColormap, &color);
+
+                    COLOR_sysPal[index] = palPtr->logpalette.palPalEntry[uStart];
+                    COLOR_sysPal[index].peFlags = flag;
+		    X11DRV_PALETTE_freeList[index] = 0;
+
+                    if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
+                    break;
+                }
+                else if ( X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_VIRTUAL ) 
+                {
+                    index = X11DRV_PALETTE_ToPhysical( NULL, 0x00ffffff &
+                             *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
+                    break;     
+                }
+
+                /* we have to map to existing entry in the system palette */
+
+                index = COLOR_PaletteLookupPixel(COLOR_sysPal, 256, NULL, 
+                       *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), TRUE);
+            }
+	    palPtr->logpalette.palPalEntry[uStart].peFlags |= PC_SYS_USED;
+
+            if( X11DRV_PALETTE_PaletteToXPixel ) index = X11DRV_PALETTE_PaletteToXPixel[index];
+            break;
+        }
+
+        if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
+        palPtr->mapping[uStart] = index;
+
+        TRACE(palette,"entry %i (%lx) -> pixel %i\n", uStart, 
+				*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
+	
+    }
+    return iRemapped;
+}
+
+/***********************************************************************
+ *           X11DRV_PALETTE_UpdateMapping
+ *
+ * Update the color-mapping table for selected palette. 
+ * Return number of entries which mapping has changed.
+ */
+int X11DRV_PALETTE_UpdateMapping(PALETTEOBJ *palPtr)
+{
+  int i, index, realized = 0;    
+  
+  for( i = 0; i < 20; i++ )
+    {
+      index = X11DRV_PALETTE_LookupSystemXPixel(*(COLORREF*)(palPtr->logpalette.palPalEntry + i));
+      
+      /* mapping is allocated in COLOR_InitPalette() */
+      
+      if( index != palPtr->mapping[i] ) { palPtr->mapping[i]=index; realized++; }
+    }
+  
+    return realized;
+}
+
+/**************************************************************************
+ *		X11DRV_PALETTE_IsDark
+ */
+BOOL X11DRV_PALETTE_IsDark(int pixel)
+{
+  COLORREF col = X11DRV_PALETTE_ToLogical(pixel);
+  return (GetRValue(col) + GetGValue(col) + GetBValue(col)) <= 0x180;
+}
+
+#endif /* !defined(X_DISPLAY_MISSING) */
diff --git a/graphics/x11drv/pen.c b/graphics/x11drv/pen.c
index f951bf8..76bb905 100644
--- a/graphics/x11drv/pen.c
+++ b/graphics/x11drv/pen.c
@@ -37,7 +37,7 @@
                     dc->wndExtX / 2) / dc->wndExtX;
     if (physDev->pen.width < 0) physDev->pen.width = -physDev->pen.width;
     if (physDev->pen.width == 1) physDev->pen.width = 0;  /* Faster */
-    physDev->pen.pixel = COLOR_ToPhysical( dc, pen->logpen.lopnColor );    
+    physDev->pen.pixel = X11DRV_PALETTE_ToPhysical( dc, pen->logpen.lopnColor );    
     switch(pen->logpen.lopnStyle & PS_STYLE_MASK)
     {
       case PS_DASH:
diff --git a/include/bitmap.h b/include/bitmap.h
index 27f0b5c..6e3894e 100644
--- a/include/bitmap.h
+++ b/include/bitmap.h
@@ -7,30 +7,9 @@
 #ifndef __WINE_BITMAP_H
 #define __WINE_BITMAP_H
 
-#include <X11/Xlib.h>
-
 #include "gdi.h"
 
-  /* Additional info for DIB section objects */
-typedef struct
-{
-    /* Windows DIB section */
-    DIBSECTION  dibSection;
-
-    /* Mapping status */
-    enum { DIB_NoHandler, DIB_InSync, DIB_AppMod, DIB_GdiMod } status;
-
-    /* Color map info */
-    int         nColorMap;
-    int        *colorMap;
-
-    /* Cached XImage */
-    XImage     *image;
-
-    /* Selector for 16-bit access to bits */
-    WORD selector;
-
-} DIBSECTIONOBJ;
+struct tagGDI_BITMAP_DRIVER;
 
 /* Flags used for BitmapBits. We only use the first two at the moment */
 
@@ -48,16 +27,24 @@
 typedef struct tagBITMAPOBJ
 {
     GDIOBJHDR   header;
-    BITMAP    bitmap;
-    SIZE      size;   /* For SetBitmapDimension() */
+    BITMAP      bitmap;
+    SIZE        size;   /* For SetBitmapDimension() */
 
-    DDBITMAP	*DDBitmap;
+    DDBITMAP   *DDBitmap;
 
     /* For device-independent bitmaps: */
-    DIBSECTIONOBJ *dib;
-
+    DIBSECTION *dib;
 } BITMAPOBJ;
 
+typedef struct tagBITMAP_DRIVER
+{
+  INT  (*pSetDIBits)(struct tagBITMAPOBJ *,struct tagDC *,UINT,UINT,LPCVOID,const BITMAPINFO *,UINT,HBITMAP);
+  INT  (*pGetDIBits)(struct tagBITMAPOBJ *,struct tagDC *,UINT,UINT,LPVOID,BITMAPINFO *,UINT,HBITMAP);
+  VOID (*pDeleteDIBSection)(struct tagBITMAPOBJ *);
+} BITMAP_DRIVER;
+
+extern BITMAP_DRIVER *BITMAP_Driver;
+
   /* objects/bitmap.c */
 extern INT16   BITMAP_GetObject16( BITMAPOBJ * bmp, INT16 count, LPVOID buffer );
 extern INT   BITMAP_GetObject( BITMAPOBJ * bmp, INT count, LPVOID buffer );
diff --git a/include/clipboard.h b/include/clipboard.h
index 7d0c282..605e357 100644
--- a/include/clipboard.h
+++ b/include/clipboard.h
@@ -1,9 +1,10 @@
 #ifndef __WINE_CLIPBOARD_H
 #define __WINE_CLIPBOARD_H
 
-#include "win.h"
 #include "windef.h"
 
+struct tagWND;
+
 typedef struct tagWINE_CLIPFORMAT {
     WORD	wFormatID;
     WORD	wRefCount;
@@ -16,15 +17,15 @@
     HANDLE16    hData16;
 } WINE_CLIPFORMAT, *LPWINE_CLIPFORMAT;
 
-typedef struct _CLIPBOARD_DRIVER
+typedef struct tagCLIPBOARD_DRIVER
 {
     void (*pEmptyClipboard)(void);
     void (*pSetClipboardData)(UINT);
     BOOL (*pRequestSelection)(void);
-    void (*pResetOwner)(WND *, BOOL);
+    void (*pResetOwner)(struct tagWND *, BOOL);
 } CLIPBOARD_DRIVER;
 
-CLIPBOARD_DRIVER *CLIPBOARD_GetDriver(void);
+extern CLIPBOARD_DRIVER *CLIPBOARD_Driver;
 
 extern void CLIPBOARD_ResetLock(HQUEUE16 hqRef, HQUEUE16 hqNew);
 extern void CLIPBOARD_DeleteRecord(LPWINE_CLIPFORMAT lpFormat, BOOL bChange);
diff --git a/include/color.h b/include/color.h
index 4907ab2..793fc2c 100644
--- a/include/color.h
+++ b/include/color.h
@@ -1,38 +1,20 @@
 #ifndef __WINE_COLOR_H
 #define __WINE_COLOR_H
 
+#include "wingdi.h"
 #include "palette.h"
-#include "gdi.h"
-
-#define COLOR_FIXED     0x0001          /* read-only colormap - have to use XAllocColor (if not virtual)*/
-#define COLOR_VIRTUAL   0x0002          /* no mapping needed - pixel == pixel color */
-
-#define COLOR_PRIVATE   0x1000          /* private colormap, identity mapping */
-#define COLOR_WHITESET	0x2000
 
 #define PC_SYS_USED     0x80		/* palentry is used (both system and logical) */
 #define PC_SYS_RESERVED 0x40		/* system palentry is not to be mapped to */
 #define PC_SYS_MAPPED   0x10		/* logical palentry is a direct alias for system palentry */
 
-extern BOOL     COLOR_Init(void);
-extern void	  COLOR_Cleanup(void);
-extern COLORREF	  COLOR_ToLogical(int pixel);
-extern int 	  COLOR_ToPhysical( DC *dc, COLORREF color );
-extern int 	  COLOR_SetMapping( PALETTEOBJ* pal, UINT uStart, UINT uNum, BOOL mapOnly );
-extern BOOL 	  COLOR_IsSolid( COLORREF color );
-extern UINT16	  COLOR_GetSystemPaletteSize(void);
-extern UINT16	  COLOR_GetSystemPaletteFlags(void);
-extern const PALETTEENTRY* COLOR_GetSystemPaletteTemplate(void);
-extern BOOL	  COLOR_GetMonoPlane( int* );
+extern BOOL  COLOR_IsSolid(COLORREF color);
 
-extern COLORREF	  COLOR_LookupNearestColor( PALETTEENTRY*, int, COLORREF );
-extern int        COLOR_PaletteLookupPixel( PALETTEENTRY*, int, int* , COLORREF, BOOL );
-extern COLORREF   COLOR_GetSystemPaletteEntry(UINT);
-extern int COLOR_LookupSystemPixel(COLORREF col);
+extern COLORREF            COLOR_GetSystemPaletteEntry(UINT);
+extern const PALETTEENTRY *COLOR_GetSystemPaletteTemplate(void);
 
-extern int 	COLOR_mapEGAPixel[16];
-extern int* 	COLOR_PaletteToPixel;
-extern int* 	COLOR_PixelToPalette;
-extern int 	COLOR_ColormapSize;
+extern COLORREF	COLOR_LookupNearestColor(PALETTEENTRY *, int, COLORREF);
+extern int      COLOR_PaletteLookupExactIndex(PALETTEENTRY *palPalEntry, int size, COLORREF col);
+extern int      COLOR_PaletteLookupPixel(PALETTEENTRY *, int, int * , COLORREF, BOOL);
 
 #endif /* __WINE_COLOR_H */
diff --git a/include/desktop.h b/include/desktop.h
index e049562..3d12481 100644
--- a/include/desktop.h
+++ b/include/desktop.h
@@ -9,10 +9,9 @@
 
 #include "windef.h"
 
+struct tagDESKTOP_DRIVER;
 struct tagMONITOR;
 
-struct _DESKTOP_DRIVER;
-
 typedef struct tagDESKTOP
 {
   HBRUSH                hbrushPattern;
@@ -20,15 +19,18 @@
   SIZE                  bitmapSize;
   BOOL                  fTileWallPaper;
   struct tagMONITOR      *pPrimaryMonitor;
-  struct _DESKTOP_DRIVER *pDriver;         /* Desktop driver */
+  struct tagDESKTOP_DRIVER *pDriver;         /* Desktop driver */
   void                   *pDriverData;     /* Desktop driver data */
 } DESKTOP;
 
-typedef struct _DESKTOP_DRIVER {
+typedef struct tagDESKTOP_DRIVER {
   void (*pInitialize)(struct tagDESKTOP *pDesktop);
   void (*pFinalize)(struct tagDESKTOP *pDesktop);
 } DESKTOP_DRIVER;
 
+extern DESKTOP_DRIVER *DESKTOP_Driver;
+
+extern BOOL DESKTOP_IsSingleWindow();
 extern int DESKTOP_GetScreenWidth(void);
 extern int DESKTOP_GetScreenHeight(void);
 extern int DESKTOP_GetScreenDepth(void);
diff --git a/include/display.h b/include/display.h
index 8aa1a11..b5830dd 100644
--- a/include/display.h
+++ b/include/display.h
@@ -7,8 +7,9 @@
 #ifndef __WINE_DISPLAY_H
 #define __WINE_DISPLAY_H
 
-#include "cursoricon.h"
-#include "wine/winuser16.h"
+#include "windef.h"
+
+struct tagCURSORICONINFO;
 
 #pragma pack(1)
 typedef struct tagCURSORINFO
@@ -18,13 +19,8 @@
 } CURSORINFO, *PCURSORINFO, *LPCURSORINFO;
 #pragma pack(4)
 
-typedef struct _MOUSE_DRIVER {
-  VOID (*pSetCursor)(CURSORICONINFO *);
-  VOID (*pMoveCursor)(WORD, WORD);
-} MOUSE_DRIVER;
-
 WORD WINAPI DISPLAY_Inquire(LPCURSORINFO lpCursorInfo);
-VOID WINAPI DISPLAY_SetCursor( CURSORICONINFO *lpCursor );
+VOID WINAPI DISPLAY_SetCursor( struct tagCURSORICONINFO *lpCursor );
 VOID WINAPI DISPLAY_MoveCursor( WORD wAbsX, WORD wAbsY );
 VOID WINAPI DISPLAY_CheckCursor();
 
diff --git a/include/gdi.h b/include/gdi.h
index 7406a32..774cf68 100644
--- a/include/gdi.h
+++ b/include/gdi.h
@@ -70,6 +70,13 @@
     WORD   colorRes;      /* 108: color resolution */    
 } DeviceCaps;
 
+typedef struct tagGDI_DRIVER 
+{
+    BOOL (*pInitialize)(void);
+    void (*pFinalize)(void);
+} GDI_DRIVER;
+
+extern GDI_DRIVER *GDI_Driver;
 
   /* Device independent DC information */
 typedef struct
@@ -159,6 +166,8 @@
     BOOL     (*pCreateBitmap)(HBITMAP); 
     BOOL     (*pCreateDC)(DC*,LPCSTR,LPCSTR,LPCSTR,const DEVMODE16*);
     BOOL     (*pDeleteDC)(DC*);
+    HBITMAP  (*pCreateDIBSection)(DC *,BITMAPINFO *,UINT,LPVOID *,HANDLE,DWORD);
+    HBITMAP16 (*pCreateDIBSection16)(DC *,BITMAPINFO *,UINT16,SEGPTR *,HANDLE,DWORD);
     BOOL     (*pDeleteObject)(HGDIOBJ);
     BOOL     (*pEllipse)(DC*,INT,INT,INT,INT);
     BOOL     (*pEnumDeviceFonts)(DC*,LPLOGFONT16,DEVICEFONTENUMPROC,LPARAM);
diff --git a/include/keyboard.h b/include/keyboard.h
index 8c249bc..1002817 100644
--- a/include/keyboard.h
+++ b/include/keyboard.h
@@ -29,15 +29,22 @@
 
 /* Wine internals */
 
-typedef struct _KEYBOARD_DRIVER {
+typedef struct tagKEYBOARD_DRIVER {
   void   (*pInit)(void);
   WORD   (*pVkKeyScan)(CHAR);
   UINT16 (*pMapVirtualKey)(UINT16, UINT16);
   INT16  (*pGetKeyNameText)(LONG, LPSTR, INT16);
   INT16  (*pToAscii)(UINT16, UINT16, LPBYTE, LPVOID, UINT16);
+  BOOL   (*pGetBeepActive)(void);
+  void   (*pSetBeepActive)(BOOL bActivate);
+  void   (*pBeep)(void);
 } KEYBOARD_DRIVER;
 
-extern KEYBOARD_DRIVER *KEYBOARD_GetDriver(void);
+extern KEYBOARD_DRIVER *KEYBOARD_Driver;
+
+extern BOOL KEYBOARD_GetBeepActive(void);
+extern void KEYBOARD_SetBeepActive(BOOL bActivate);
+extern void KEYBOARD_Beep(void);
 
 extern void KEYBOARD_SendEvent(BYTE bVk, BYTE bScan, DWORD dwFlags, DWORD posX, DWORD posY, DWORD time);
 
diff --git a/include/message.h b/include/message.h
index 6c54bb4..ffe942e 100644
--- a/include/message.h
+++ b/include/message.h
@@ -32,21 +32,22 @@
 #define EVENT_IO_EXCEPT		2
 
 /* event.c */
-
-typedef struct _EVENT_DRIVER {
-  BOOL (*pInit)(void);
+typedef struct tagEVENT_DRIVER {
+  BOOL   (*pInit)(void);
   void   (*pAddIO)(int, unsigned);
   void   (*pDeleteIO)(int, unsigned);
-  BOOL (*pWaitNetEvent)(BOOL, BOOL);
+  BOOL   (*pWaitNetEvent)(BOOL, BOOL);
   void   (*pSynchronize)(void);
-  BOOL (*pCheckFocus)(void);
-  BOOL (*pQueryPointer)(DWORD *, DWORD *, DWORD *);
+  BOOL   (*pCheckFocus)(void);
+  BOOL   (*pQueryPointer)(DWORD *, DWORD *, DWORD *);
   void   (*pDummyMotionNotify)(void);
-  BOOL (*pPending)(void);
+  BOOL   (*pPending)(void);
   BOOL16 (*pIsUserIdle)(void);
   void   (*pWakeUp)(void);
 } EVENT_DRIVER;
 
+extern EVENT_DRIVER *EVENT_Driver;
+
 extern void EVENT_AddIO( int fd, unsigned flag );
 extern void EVENT_DeleteIO( int fd, unsigned flag );
 extern BOOL EVENT_Init( void );
diff --git a/include/monitor.h b/include/monitor.h
index ae5f8e1..ec37bbf 100644
--- a/include/monitor.h
+++ b/include/monitor.h
@@ -6,28 +6,42 @@
 #ifndef __WINE_MONITOR_H
 #define __WINE_MONITOR_H
 
+#include "windef.h"
+
 struct tagMONITOR_DRIVER;
 
 typedef struct tagMONITOR 
 {
-  struct tagMONITOR_DRIVER *pDriver;
-  void                     *pDriverData;
+  void *pDriverData;
 } MONITOR;
 
 typedef struct tagMONITOR_DRIVER {
-  void (*pInitialize)(MONITOR *);
-  void (*pFinalize)(MONITOR *);
-  int  (*pGetWidth)(MONITOR *);
-  int  (*pGetHeight)(MONITOR *);
-  int  (*pGetDepth)(MONITOR *);
+  void   (*pInitialize)(struct tagMONITOR *);
+  void   (*pFinalize)(struct tagMONITOR *);
+  BOOL   (*pIsSingleWindow)(struct tagMONITOR *);
+  int    (*pGetWidth)(struct tagMONITOR *);
+  int    (*pGetHeight)(struct tagMONITOR *);
+  int    (*pGetDepth)(struct tagMONITOR *);
+  BOOL   (*pGetScreenSaveActive)(struct tagMONITOR *);
+  void   (*pSetScreenSaveActive)(struct tagMONITOR *, BOOL);
+  int    (*pGetScreenSaveTimeout)(struct tagMONITOR *);
+  void   (*pSetScreenSaveTimeout)(struct tagMONITOR *, int);
 } MONITOR_DRIVER;
 
+extern MONITOR_DRIVER *MONITOR_Driver;
+
 extern MONITOR MONITOR_PrimaryMonitor;
 
 extern void MONITOR_Initialize(MONITOR *pMonitor);
 extern void MONITOR_Finalize(MONITOR *pMonitor);
+extern BOOL MONITOR_IsSingleWindow(MONITOR *pMonitor);
 extern int MONITOR_GetWidth(MONITOR *pMonitor);
 extern int MONITOR_GetHeight(MONITOR *pMonitor);
 extern int MONITOR_GetDepth(MONITOR *pMonitor);
+extern BOOL MONITOR_GetScreenSaveActive(MONITOR *pMonitor);
+extern void MONITOR_SetScreenSaveActive(MONITOR *pMonitor, BOOL bActivate);
+extern int MONITOR_GetScreenSaveTimeout(MONITOR *pMonitor);
+extern void MONITOR_SetScreenSaveTimeout(MONITOR *pMonitor, int nTimeout);
 
 #endif /* __WINE_MONITOR_H */
+
diff --git a/include/mouse.h b/include/mouse.h
index 1de96dd..2b7d18d 100644
--- a/include/mouse.h
+++ b/include/mouse.h
@@ -7,6 +7,10 @@
 #ifndef __WINE_MOUSE_H
 #define __WINE_MOUSE_H
 
+#include "windef.h"
+
+struct tagCURSORICONINFO;
+
 #pragma pack(1)
 typedef struct _MOUSEINFO
 {
@@ -30,6 +34,14 @@
 
 /* Wine internals */
 
+typedef struct tagMOUSE_DRIVER {
+  VOID (*pSetCursor)(struct tagCURSORICONINFO *);
+  VOID (*pMoveCursor)(WORD, WORD);
+  BOOL (*pEnableWarpPointer)(BOOL);
+} MOUSE_DRIVER;
+
+extern MOUSE_DRIVER *MOUSE_Driver;
+
 #define WINE_MOUSEEVENT_MAGIC  ( ('M'<<24)|('A'<<16)|('U'<<8)|'S' )
 typedef struct _WINE_MOUSEEVENT
 {
diff --git a/include/palette.h b/include/palette.h
index c6e4cfb..a7011f1 100644
--- a/include/palette.h
+++ b/include/palette.h
@@ -12,13 +12,22 @@
 #define NB_RESERVED_COLORS              20 /* number of fixed colors in system palette */
 
   /* GDI logical palette object */
-typedef struct
+typedef struct tagPALETTEOBJ
 {
-    GDIOBJHDR   header;
-    int        *mapping;
-    LOGPALETTE  logpalette; /* _MUST_ be the last field */
+    GDIOBJHDR                    header;
+    int                          *mapping;
+    LOGPALETTE                   logpalette; /* _MUST_ be the last field */
 } PALETTEOBJ;
 
+typedef struct tagPALETTE_DRIVER
+{
+  int  (*pSetMapping)(struct tagPALETTEOBJ *, UINT, UINT, BOOL);
+  int  (*pUpdateMapping)(struct tagPALETTEOBJ *);
+  BOOL (*pIsDark)(int pixel);
+} PALETTE_DRIVER;
+
+extern PALETTE_DRIVER *PALETTE_Driver;
+
 extern HPALETTE16 PALETTE_Init(void);
 extern int PALETTE_GetObject( PALETTEOBJ * palette, int count, LPSTR buffer );
 extern BOOL PALETTE_DeleteObject( HPALETTE16 hpalette, PALETTEOBJ *palette );
diff --git a/include/sysmetrics.h b/include/sysmetrics.h
index 376528a..811e6ac 100644
--- a/include/sysmetrics.h
+++ b/include/sysmetrics.h
@@ -7,7 +7,8 @@
 #ifndef __WINE_SYSMETRICS_H
 #define __WINE_SYSMETRICS_H
 
-#include "windef.h"
+#include "wingdi.h"
+
   /* Constant system metrics */
 #if 0
 #ifdef WIN_95_LOOK
diff --git a/include/ttydrv.h b/include/ttydrv.h
index abef5bc..d66997f 100644
--- a/include/ttydrv.h
+++ b/include/ttydrv.h
@@ -6,27 +6,67 @@
 #define __WINE_TTYDRV_H
 
 #include "windef.h"
+#include "wingdi.h"
 #include "wine/winuser16.h"
 
+struct tagBITMAPOBJ;
 struct tagCLASS;
 struct tagDC;
 struct tagDESKTOP;
+struct tagPALETTEOBJ;
 struct tagWND;
 
-/* TTY GDI driver */
+/**************************************************************************
+ * TTY GDI driver
+ */
 
-typedef struct {
-} TTYDRV_PDEVICE;
+extern struct tagGDI_DRIVER TTYDRV_GDI_Driver;
 
 extern BOOL TTYDRV_GDI_Initialize(void);
-extern void TTDRV_GDI_Finalize(void);
-extern BOOL TTYDRV_GDI_CreateDC(struct tagDC *dc, LPCSTR driver, LPCSTR device, LPCSTR output, const DEVMODE16 *initData);
-extern BOOL TTYDRV_GDI_DeleteDC(struct tagDC *dc);
-extern INT TTYDRV_GDI_Escape(struct tagDC *dc, INT nEscape, INT cbInput, SEGPTR lpInData, SEGPTR lpOutData);
+extern void TTYDRV_GDI_Finalize(void);
+
+/* TTY GDI bitmap driver */
+
+extern HBITMAP TTYDRV_BITMAP_CreateDIBSection(struct tagDC *dc, BITMAPINFO *bmi, UINT usage, LPVOID *bits, HANDLE section, DWORD offset);
+extern HBITMAP16 TTYDRV_BITMAP_CreateDIBSection16(struct tagDC *dc, BITMAPINFO *bmi, UINT16 usage, SEGPTR *bits, HANDLE section, DWORD offset);
+
+extern INT TTYDRV_BITMAP_SetDIBits(struct tagBITMAPOBJ *bmp, struct tagDC *dc, UINT startscan, UINT lines, LPCVOID bits, const BITMAPINFO *info, UINT coloruse, HBITMAP hbitmap);
+extern INT TTYDRV_BITMAP_GetDIBits(struct tagBITMAPOBJ *bmp, struct tagDC *dc, UINT startscan, UINT lines, LPVOID bits, BITMAPINFO *info, UINT coloruse, HBITMAP hbitmap);
+extern void TTYDRV_BITMAP_DeleteDIBSection(struct tagBITMAPOBJ *bmp);
+
+typedef struct {
+  int dummy;
+} TTYDRV_PDEVICE;
+
+extern BOOL TTYDRV_DC_CreateDC(struct tagDC *dc, LPCSTR driver, LPCSTR device, LPCSTR output, const DEVMODE16 *initData);
+extern BOOL TTYDRV_DC_DeleteDC(struct tagDC *dc);
+extern INT TTYDRV_DC_Escape(struct tagDC *dc, INT nEscape, INT cbInput, SEGPTR lpInData, SEGPTR lpOutData);
+
+/* TTY GDI palette driver */
+
+extern struct tagPALETTE_DRIVER TTYDRV_PALETTE_Driver;
+
+extern BOOL TTYDRV_PALETTE_Initialize(void);
+extern void TTYDRV_PALETTE_Finalize(void);
+
+extern int TTYDRV_PALETTE_SetMapping(struct tagPALETTEOBJ *palPtr, UINT uStart, UINT uNum, BOOL mapOnly);
+extern int TTYDRV_PALETTE_UpdateMapping(struct tagPALETTEOBJ *palPtr);
+extern BOOL TTYDRV_PALETTE_IsDark(int pixel);
+
+/**************************************************************************
+ * TTY USER driver
+ */
+
+extern struct tagUSER_DRIVER TTYDRV_USER_Driver;
+
+extern BOOL TTYDRV_USER_Initialize(void);
+extern void TTYDRV_USER_Finalize(void);
+extern void TTYDRV_USER_BeginDebugging(void);
+extern void TTYDRV_USER_EndDebugging(void);
 
 /* TTY clipboard driver */
 
-extern struct _CLIPBOARD_DRIVER TTYDRV_CLIPBOARD_Driver;
+extern struct tagCLIPBOARD_DRIVER TTYDRV_CLIPBOARD_Driver;
 
 extern void TTYDRV_CLIPBOARD_EmptyClipboard(void);
 extern void TTYDRV_CLIPBOARD_SetClipboardData(UINT wFormat);
@@ -35,7 +75,7 @@
 
 /* TTY desktop driver */
 
-extern struct _DESKTOP_DRIVER TTYDRV_DESKTOP_Driver;
+extern struct tagDESKTOP_DRIVER TTYDRV_DESKTOP_Driver;
 
 extern void TTYDRV_DESKTOP_Initialize(struct tagDESKTOP *pDesktop);
 extern void TTYDRV_DESKTOP_Finalize(struct tagDESKTOP *pDesktop);
@@ -45,7 +85,7 @@
 
 /* TTY event driver */
 
-extern struct _EVENT_DRIVER TTYDRV_EVENT_Driver;
+extern struct tagEVENT_DRIVER TTYDRV_EVENT_Driver;
 
 extern BOOL TTYDRV_EVENT_Init(void);
 extern void TTYDRV_EVENT_AddIO(int fd, unsigned flag);
@@ -61,22 +101,16 @@
 
 /* TTY keyboard driver */
 
-extern struct _KEYBOARD_DRIVER TTYDRV_KEYBOARD_Driver;
+extern struct tagKEYBOARD_DRIVER TTYDRV_KEYBOARD_Driver;
 
 extern void TTYDRV_KEYBOARD_Init(void);
 extern WORD TTYDRV_KEYBOARD_VkKeyScan(CHAR cChar);
 extern UINT16 TTYDRV_KEYBOARD_MapVirtualKey(UINT16 wCode, UINT16 wMapType);
 extern INT16 TTYDRV_KEYBOARD_GetKeyNameText(LONG lParam, LPSTR lpBuffer, INT16 nSize);
 extern INT16 TTYDRV_KEYBOARD_ToAscii(UINT16 virtKey, UINT16 scanCode, LPBYTE lpKeyState, LPVOID lpChar, UINT16 flags);
-
-/* TTY main driver */
-
-extern void TTYDRV_MAIN_Finalize(void);
-extern void TTYDRV_MAIN_Initialize(void);
-extern void TTYDRV_MAIN_ParseOptions(int *argc, char *argv[]);
-extern void TTYDRV_MAIN_Create(void);
-extern void TTYDRV_MAIN_SaveSetup(void);
-extern void TTYDRV_MAIN_RestoreSetup(void);
+extern BOOL TTYDRV_KEYBOARD_GetBeepActive(void);
+extern void TTYDRV_KEYBOARD_SetBeepActive(BOOL bActivate);
+extern void TTYDRV_KEYBOARD_Beep(void);
 
 /* TTY monitor driver */
 
@@ -92,20 +126,26 @@
 
 extern void TTYDRV_MONITOR_Initialize(struct tagMONITOR *pMonitor);
 extern void  TTYDRV_MONITOR_Finalize(struct tagMONITOR *pMonitor);
+extern BOOL TTYDRV_MONITOR_IsSingleWindow(struct tagMONITOR *pMonitor);
 extern int TTYDRV_MONITOR_GetWidth(struct tagMONITOR *pMonitor);
 extern int TTYDRV_MONITOR_GetHeight(struct tagMONITOR *pMonitor);
 extern int TTYDRV_MONITOR_GetDepth(struct tagMONITOR *pMonitor);
+extern BOOL TTYDRV_MONITOR_GetScreenSaveActive(struct tagMONITOR *pMonitor);
+extern void TTYDRV_MONITOR_SetScreenSaveActive(struct tagMONITOR *pMonitor, BOOL bActivate);
+extern int TTYDRV_MONITOR_GetScreenSaveTimeout(struct tagMONITOR *pMonitor);
+extern void TTYDRV_MONITOR_SetScreenSaveTimeout(struct tagMONITOR *pMonitor, int nTimeout);
 
 /* TTY mouse driver */
 
-extern struct _MOUSE_DRIVER TTYDRV_MOUSE_Driver;
+extern struct tagMOUSE_DRIVER TTYDRV_MOUSE_Driver;
 
 extern void TTYDRV_MOUSE_SetCursor(CURSORICONINFO *lpCursor);
 extern void TTYDRV_MOUSE_MoveCursor(WORD wAbsX, WORD wAbsY);
+extern BOOL TTYDRV_MOUSE_EnableWarpPointer(BOOL bEnable);
 
 /* TTY windows driver */
 
-extern struct _WND_DRIVER TTYDRV_WND_Driver;
+extern struct tagWND_DRIVER TTYDRV_WND_Driver;
 
 extern void TTYDRV_WND_Initialize(struct tagWND *wndPtr);
 extern void TTYDRV_WND_Finalize(struct tagWND *wndPtr);
diff --git a/include/user.h b/include/user.h
index 2e9923c..f7ab2ba 100644
--- a/include/user.h
+++ b/include/user.h
@@ -29,6 +29,15 @@
 #define USUD_LOCALHEAP         0x0004
 #define USUD_FIRSTCLASS        0x0005
 
+typedef struct tagUSER_DRIVER {
+  BOOL (*pInitialize)(void);
+  void (*pFinalize)(void);
+  void (*pBeginDebugging)(void);
+  void (*pEndDebugging)(void);
+} USER_DRIVER;
+
+extern USER_DRIVER *USER_Driver;
+
 void WINAPI USER_SignalProc(HANDLE16, UINT16, UINT16, HINSTANCE16, HQUEUE16);
 void USER_ExitWindows(void);
 void USER_QueueCleanup( HQUEUE16 hQueue );
diff --git a/include/win.h b/include/win.h
index 5d166842..1c37a53 100644
--- a/include/win.h
+++ b/include/win.h
@@ -52,7 +52,7 @@
 struct tagCLASS;
 struct tagDCE;
 struct tagDC;
-struct _WND_DRIVER;
+struct tagWND_DRIVER;
 
 typedef struct tagWND
 {
@@ -83,7 +83,7 @@
     HMENU16        hSysMenu;      /* window's copy of System Menu */
     int            irefCount;     /* window's reference count*/
     DWORD          userdata;      /* User private data */
-    struct _WND_DRIVER *pDriver;  /* Window driver */
+    struct tagWND_DRIVER *pDriver;  /* Window driver */
     void          *pDriverData;   /* Window driver data */
     DWORD          wExtra[1];     /* Window extra bytes */
 } WND;
@@ -107,7 +107,7 @@
 #define BGSouthEast        9
 #define BGStatic           10
 
-typedef struct _WND_DRIVER
+typedef struct tagWND_DRIVER
 {
     void   (*pInitialize)(WND *);
     void   (*pFinalize)(WND *);
@@ -127,6 +127,8 @@
     BOOL (*pIsSelfClipping)(WND *);
 } WND_DRIVER;
 
+extern WND_DRIVER *WND_Driver;
+
 typedef struct
 {
     RECT16	   rectNormal;
diff --git a/include/x11drv.h b/include/x11drv.h
index deb9270..4b9a967 100644
--- a/include/x11drv.h
+++ b/include/x11drv.h
@@ -1,5 +1,5 @@
 /*
- * X11 display driver definitions
+ * X11 driver definitions
  */
 
 #ifndef __WINE_X11DRV_H
@@ -18,13 +18,15 @@
 #include "gdi.h"
 #include "windef.h"
 
+struct tagBITMAPOBJ;
 struct tagCLASS;
+struct tagCREATESTRUCTA;
+struct tagCURSORICONINFO;
 struct tagDC;
 struct tagDeviceCaps;
+struct tagPALETTEOBJ;
 struct tagWND;
-struct tagCREATESTRUCTA;
 struct tagWINDOWPOS;
-struct tagCURSORICONINFO;
 
   /* X physical pen */
 typedef struct
@@ -74,6 +76,7 @@
 #define BITMAP_GC(bmp) \
   (((bmp)->bitmap.bmBitsPixel == 1) ? BITMAP_monoGC : BITMAP_colorGC)
 
+extern DeviceCaps X11DRV_DevCaps;
 
 /* Wine driver X11 functions */
 
@@ -188,6 +191,26 @@
 
 /* exported dib functions for now */
 
+/* Additional info for DIB section objects */
+typedef struct
+{
+    /* Windows DIB section */
+    DIBSECTION  dibSection;
+
+    /* Mapping status */
+    enum { X11DRV_DIB_NoHandler, X11DRV_DIB_InSync, X11DRV_DIB_AppMod, X11DRV_DIB_GdiMod } status;
+
+    /* Color map info */
+    int         nColorMap;
+    int        *colorMap;
+
+    /* Cached XImage */
+    XImage     *image;
+
+    /* Selector for 16-bit access to bits */
+    WORD selector;
+} X11DRV_DIBSECTION;
+
 /* This structure holds the arguments for DIB_SetImageBits() */
 typedef struct
 {
@@ -209,17 +232,86 @@
     int               yDest;
     int               width;
     int               height;
-} DIB_SETIMAGEBITS_DESCR;
+} X11DRV_DIB_SETIMAGEBITS_DESCR;
 
-extern int X11DRV_DIB_GetImageBits( const DIB_SETIMAGEBITS_DESCR *descr );
-extern int X11DRV_DIB_SetImageBits( const DIB_SETIMAGEBITS_DESCR *descr );
+extern int X11DRV_DIB_GetImageBits( const X11DRV_DIB_SETIMAGEBITS_DESCR *descr );
+extern int X11DRV_DIB_SetImageBits( const X11DRV_DIB_SETIMAGEBITS_DESCR *descr );
 extern int *X11DRV_DIB_BuildColorMap( struct tagDC *dc, WORD coloruse,
 				      WORD depth, const BITMAPINFO *info,
 				      int *nColors );
+extern void X11DRV_DIB_UpdateDIBSection(struct tagDC *dc, BOOL toDIB);
+
+extern HBITMAP X11DRV_DIB_CreateDIBSection(struct tagDC *dc, BITMAPINFO *bmi, UINT usage,
+					   LPVOID *bits, HANDLE section, DWORD offset);
+extern HBITMAP16 X11DRV_DIB_CreateDIBSection16(struct tagDC *dc, BITMAPINFO *bmi, UINT16 usage,
+					       SEGPTR *bits, HANDLE section, DWORD offset);
+
+extern struct tagBITMAP_DRIVER X11DRV_BITMAP_Driver;
+
+extern INT X11DRV_DIB_SetDIBits(struct tagBITMAPOBJ *bmp, struct tagDC *dc, UINT startscan,
+				UINT lines, LPCVOID bits, const BITMAPINFO *info,
+				UINT coloruse, HBITMAP hbitmap);
+extern INT X11DRV_DIB_GetDIBits(struct tagBITMAPOBJ *bmp, struct tagDC *dc, UINT startscan,
+				UINT lines, LPVOID bits, BITMAPINFO *info,
+				UINT coloruse, HBITMAP hbitmap);
+extern void X11DRV_DIB_DeleteDIBSection(struct tagBITMAPOBJ *bmp);
+
+/**************************************************************************
+ * X11 GDI driver
+ */
+
+extern struct tagGDI_DRIVER X11DRV_GDI_Driver;
+
+BOOL X11DRV_GDI_Initialize(void);
+void X11DRV_GDI_Finalize(void);
+
+/* X11 GDI palette driver */
+
+#define X11DRV_PALETTE_FIXED    0x0001 /* read-only colormap - have to use XAllocColor (if not virtual)*/
+#define X11DRV_PALETTE_VIRTUAL  0x0002 /* no mapping needed - pixel == pixel color */
+
+#define X11DRV_PALETTE_PRIVATE  0x1000 /* private colormap, identity mapping */
+#define X11DRV_PALETTE_WHITESET 0x2000
+
+extern Colormap X11DRV_PALETTE_PaletteXColormap;
+extern UINT16 X11DRV_PALETTE_PaletteFlags;
+
+extern int *X11DRV_PALETTE_PaletteToXPixel;
+extern int *X11DRV_PALETTE_XPixelToPalette;
+
+extern int X11DRV_PALETTE_mapEGAPixel[16];
+
+extern BOOL X11DRV_PALETTE_Init(void);
+extern void X11DRV_PALETTE_Cleanup(void);
+
+extern COLORREF X11DRV_PALETTE_ToLogical(int pixel);
+extern int X11DRV_PALETTE_ToPhysical(struct tagDC *dc, COLORREF color);
+extern int X11DRV_PALETTE_LookupSystemXPixel(COLORREF col);
+
+extern struct tagPALETTE_DRIVER X11DRV_PALETTE_Driver;
+
+extern int X11DRV_PALETTE_SetMapping(struct tagPALETTEOBJ *palPtr, UINT uStart, UINT uNum, BOOL mapOnly);
+extern int X11DRV_PALETTE_UpdateMapping(struct tagPALETTEOBJ *palPtr);
+extern BOOL X11DRV_PALETTE_IsDark(int pixel);
+
+/**************************************************************************
+ * X11 USER driver
+ */
+
+extern struct tagUSER_DRIVER X11DRV_USER_Driver;
+
+extern Display *display;
+extern Screen *X11DRV_GetXScreen(void);
+extern Window X11DRV_GetXRootWindow(void);
+
+extern BOOL X11DRV_USER_Initialize(void);
+extern void X11DRV_USER_Finalize(void);
+extern void X11DRV_USER_BeginDebugging(void);
+extern void X11DRV_USER_EndDebugging(void);
 
 /* X11 clipboard driver */
 
-extern struct _CLIPBOARD_DRIVER X11DRV_CLIPBOARD_Driver;
+extern struct tagCLIPBOARD_DRIVER X11DRV_CLIPBOARD_Driver;
 
 extern void X11DRV_CLIPBOARD_EmptyClipboard(void);
 extern void X11DRV_CLIPBOARD_SetClipboardData(UINT wFormat);
@@ -229,15 +321,12 @@
 void X11DRV_CLIPBOARD_ReadSelection(Window w, Atom prop);
 void X11DRV_CLIPBOARD_ReleaseSelection(Window w, HWND hwnd);
 
-/* X11 color driver */
-
-extern Colormap	X11DRV_COLOR_GetColormap(void);
-
 /* X11 desktop driver */
 
-extern struct _DESKTOP_DRIVER X11DRV_DESKTOP_Driver;
+extern struct tagDESKTOP_DRIVER X11DRV_DESKTOP_Driver;
 
 typedef struct _X11DRV_DESKTOP_DATA {
+  int dummy;
 } X11DRV_DESKTOP_DATA;
 
 struct tagDESKTOP;
@@ -253,7 +342,7 @@
 
 /* X11 event driver */
 
-extern struct _EVENT_DRIVER X11DRV_EVENT_Driver;
+extern struct tagEVENT_DRIVER X11DRV_EVENT_Driver;
 
 extern BOOL X11DRV_EVENT_Init(void);
 extern void X11DRV_EVENT_AddIO(int fd, unsigned flag);
@@ -269,28 +358,18 @@
 
 /* X11 keyboard driver */
 
-extern struct _KEYBOARD_DRIVER X11DRV_KEYBOARD_Driver;
+extern struct tagKEYBOARD_DRIVER X11DRV_KEYBOARD_Driver;
 
 extern void X11DRV_KEYBOARD_Init(void);
 extern WORD X11DRV_KEYBOARD_VkKeyScan(CHAR cChar);
 extern UINT16 X11DRV_KEYBOARD_MapVirtualKey(UINT16 wCode, UINT16 wMapType);
 extern INT16 X11DRV_KEYBOARD_GetKeyNameText(LONG lParam, LPSTR lpBuffer, INT16 nSize);
 extern INT16 X11DRV_KEYBOARD_ToAscii(UINT16 virtKey, UINT16 scanCode, LPBYTE lpKeyState, LPVOID lpChar, UINT16 flags);
-extern void KEYBOARD_HandleEvent( struct tagWND *pWnd, XKeyEvent *event );
-extern void KEYBOARD_UpdateState ( void );
+extern BOOL X11DRV_KEYBOARD_GetBeepActive(void);
+extern void X11DRV_KEYBOARD_SetBeepActive(BOOL bActivate);
+extern void X11DRV_KEYBOARD_Beep(void);
 
-/* X11 main driver */
-
-extern Display *display;
-extern Screen *X11DRV_GetXScreen(void);
-extern Window X11DRV_GetXRootWindow(void);
-
-extern void X11DRV_MAIN_Finalize(void);
-extern void X11DRV_MAIN_Initialize(void);
-extern void X11DRV_MAIN_ParseOptions(int *argc, char *argv[]);
-extern void X11DRV_MAIN_Create(void);
-extern void X11DRV_MAIN_SaveSetup(void);
-extern void X11DRV_MAIN_RestoreSetup(void);
+extern void X11DRV_KEYBOARD_HandleEvent(struct tagWND *pWnd, XKeyEvent *event);
 
 /* X11 monitor driver */
 
@@ -311,20 +390,28 @@
 
 extern void X11DRV_MONITOR_Initialize(struct tagMONITOR *pMonitor);
 extern void X11DRV_MONITOR_Finalize(struct tagMONITOR *pMonitor);
+extern BOOL X11DRV_MONITOR_IsSingleWindow(struct tagMONITOR *pMonitor);
 extern int X11DRV_MONITOR_GetWidth(struct tagMONITOR *pMonitor);
 extern int X11DRV_MONITOR_GetHeight(struct tagMONITOR *pMonitor);
 extern int X11DRV_MONITOR_GetDepth(struct tagMONITOR *pMonitor);
+extern BOOL X11DRV_MONITOR_GetScreenSaveActive(struct tagMONITOR *pMonitor);
+extern void X11DRV_MONITOR_SetScreenSaveActive(struct tagMONITOR *pMonitor, BOOL bActivate);
+extern int X11DRV_MONITOR_GetScreenSaveTimeout(struct tagMONITOR *pMonitor);
+extern void X11DRV_MONITOR_SetScreenSaveTimeout(struct tagMONITOR *pMonitor, int nTimeout);
 
 /* X11 mouse driver */
 
-extern struct _MOUSE_DRIVER X11DRV_MOUSE_Driver;
+extern struct tagMOUSE_DRIVER X11DRV_MOUSE_Driver;
+
+extern BOOL X11DRV_MOUSE_DisableWarpPointer;
 
 extern void X11DRV_MOUSE_SetCursor(struct tagCURSORICONINFO *lpCursor);
 extern void X11DRV_MOUSE_MoveCursor(WORD wAbsX, WORD wAbsY);
+extern BOOL X11DRV_MOUSE_EnableWarpPointer(BOOL bEnable);
 
 /* X11 windows driver */
 
-extern struct _WND_DRIVER X11DRV_WND_Driver;
+extern struct tagWND_DRIVER X11DRV_WND_Driver;
 
 typedef struct _X11DRV_WND_DATA {
   Window window;
diff --git a/misc/main.c b/misc/main.c
index a09b751..e759b7c 100644
--- a/misc/main.c
+++ b/misc/main.c
@@ -7,11 +7,10 @@
 #include "config.h"
 
 #ifndef X_DISPLAY_MISSING
-#include "ts_xlib.h"
 #include "x11drv.h"
-#else /* X_DISPLAY_MISSING */
+#else /* !defined(X_DISPLAY_MISSING) */
 #include "ttydrv.h"
-#endif /* X_DISPLAY_MISSING */
+#endif /* !defined(X_DISPLAY_MISSING) */
 
 #include <locale.h>
 #include <ctype.h>
@@ -21,7 +20,7 @@
 #ifdef MALLOC_DEBUGGING
 # include <malloc.h>
 #endif
-#include "wine/winuser16.h"
+
 #include "winbase.h"
 #include "winsock.h"
 #include "heap.h"
@@ -39,6 +38,14 @@
 #include "winnls.h"
 #include "console.h"
 #include "monitor.h"
+#include "keyboard.h"
+#include "gdi.h"
+#include "user.h"
+#include "wine/winuser16.h"
+
+/**********************************************************************/
+
+USER_DRIVER *USER_Driver = NULL;
 
 /* when adding new languages look at ole/ole2nls.c 
  * for proper iso name and Windows code (add 0x0400 
@@ -100,7 +107,6 @@
 static char szUsage[] =
   "%s\n"
   "Usage:  %s [options] \"program_name [arguments]\"\n"
-#ifndef X_DISPLAY_MISSING
   "\n"
   "Options:\n"
   "    -backingstore   Turn on backing store\n"
@@ -128,7 +134,6 @@
   "    -version        Display the Wine version\n"
   "    -winver         Version to imitate (one of win31,win95,nt351,nt40)\n"
   "    -dosver         DOS version to imitate (x.xx, e.g. 6.22). Only valid with -winver win31\n"
-#endif /* X_DISPLAY_MISSING */
   ;
 
 /***********************************************************************
@@ -744,12 +749,6 @@
             exit(0);
         }
     }
-
-#ifndef X_DISPLAY_MISSING
-    X11DRV_MAIN_ParseOptions(argc,argv);
-#else /* X_DISPLAY_MISSING */
-    TTYDRV_MAIN_ParseOptions(argc,argv);
-#endif /* X_DISPLAY_MISSING */
 }
 
 /***********************************************************************
@@ -757,12 +756,9 @@
  */
 static void called_at_exit(void)
 {
-#ifndef X_DISPLAY_MISSING
-    X11DRV_MAIN_RestoreSetup();
-#else /* X_DISPLAY_MISSING */
-    TTYDRV_MAIN_RestoreSetup();
-#endif /* X_DISPLAY_MISSING */
-    COLOR_Cleanup();
+    GDI_Driver->pFinalize();
+    USER_Driver->pFinalize();
+
     WINSOCK_Shutdown();
     CONSOLE_Close();
 }
@@ -798,23 +794,16 @@
     gettimeofday( &tv, NULL);
     MSG_WineStartTicks = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
     
-#ifndef X_DISPLAY_MISSING
-    X11DRV_MAIN_Initialize();
-    MAIN_ParseOptions( argc, argv );
-    X11DRV_MAIN_Create();
-    X11DRV_MAIN_SaveSetup();
-#else /* !defined(X_DISPLAY_MISSING) */
-    TTYDRV_MAIN_Initialize();
-    MAIN_ParseOptions( argc, argv );
-    TTYDRV_MAIN_Create();
-    TTYDRV_MAIN_SaveSetup();
-#endif /* !defined(X_DISPLAY_MISSING) */
+    MAIN_ParseOptions(argc, argv);
 
 #ifndef X_DISPLAY_MISSING
-    MONITOR_PrimaryMonitor.pDriver = &X11DRV_MONITOR_Driver;
+    USER_Driver = &X11DRV_USER_Driver;
 #else /* !defined(X_DISPLAY_MISSING) */
-    MONITOR_PrimaryMonitor.pDriver = &TTYDRV_MONITOR_Driver;
+    USER_Driver = &TTYDRV_USER_Driver;
 #endif /* !defined(X_DISPLAY_MISSING) */
+
+    USER_Driver->pInitialize();
+
     MONITOR_Initialize(&MONITOR_PrimaryMonitor);
 
     if (Options.dllFlags)
@@ -839,7 +828,7 @@
  */
 BOOL WINAPI MessageBeep( UINT i )
 {
-    TSXBell( display, 0 );
+    KEYBOARD_Beep();
     return TRUE;
 }
 
@@ -850,7 +839,7 @@
 BOOL WINAPI Beep( DWORD dwFreq, DWORD dwDur )
 {
     /* dwFreq and dwDur are ignored by Win95 */
-    TSXBell(display, 0);
+    KEYBOARD_Beep();
     return TRUE;
 }
 
@@ -870,17 +859,14 @@
                                        LPVOID lpvParam, UINT fuWinIni )
 {
 	int timeout;
-	int temp;
-	XKeyboardState		keyboard_state;
 
 	switch (uAction) {
 	case SPI_GETBEEP:
-		TSXGetKeyboardControl(display, &keyboard_state);
-		if (keyboard_state.bell_percent == 0)
-			*(BOOL *) lpvParam = FALSE;
-		else
-			*(BOOL *) lpvParam = TRUE;
+	        *(BOOL *) lpvParam = KEYBOARD_GetBeepActive();
 		break;
+	case SPI_SETBEEP:
+	       KEYBOARD_SetBeepActive(uParam);
+	       break;
 
 	case SPI_GETBORDER:
 		*(INT *)lpvParam = GetSystemMetrics( SM_CXFRAME );
@@ -920,19 +906,18 @@
 		*(BOOL*)lpvParam=GetSystemMetrics(SM_MENUDROPALIGNMENT); /* XXX check this */
 		break;
 
-	case SPI_GETSCREENSAVEACTIVE:
-		if ( GetProfileIntA( "windows", "ScreenSaveActive", 1 ) == 1 )
-			*(BOOL*)lpvParam = TRUE;
+	case SPI_GETSCREENSAVEACTIVE:	        
+	       if(MONITOR_GetScreenSaveActive(&MONITOR_PrimaryMonitor) || 
+		  GetProfileIntA( "windows", "ScreenSaveActive", 1 ) == 1)
+	        	*(BOOL*)lpvParam = TRUE;
 		else
 			*(BOOL*)lpvParam = FALSE;
 		break;
 
 	case SPI_GETSCREENSAVETIMEOUT:
-#ifndef X_DISPLAY_MISSING
-	        TSXGetScreenSaver(display, &timeout, &temp,&temp,&temp);
-#else /* X_DISPLAY_MISSING */
-		timeout = GetProfileIntA( "windows", "ScreenSaveTimeout", 300 );
-#endif /* X_DISPLAY_MISSING */
+	        timeout = MONITOR_GetScreenSaveTimeout(&MONITOR_PrimaryMonitor);
+		if(!timeout)
+			timeout = GetProfileIntA( "windows", "ScreenSaveTimeout", 300 );
 		*(INT *) lpvParam = timeout * 1000;
 		break;
 
@@ -1056,18 +1041,11 @@
 {
 	int timeout; 
 	char buffer[256];
-	int temp;
-	XKeyboardState		keyboard_state;
-	XKeyboardControl	keyboard_value;
 
 	switch (uAction)
         {
 		case SPI_GETBEEP:
-			TSXGetKeyboardControl(display, &keyboard_state);
-			if (keyboard_state.bell_percent == 0)
-				*(BOOL16 *) lpvParam = FALSE;
-			else
-				*(BOOL16 *) lpvParam = TRUE;
+  		        *(BOOL *) lpvParam = KEYBOARD_GetBeepActive();
 			break;
 		
 		case SPI_GETBORDER:
@@ -1109,18 +1087,17 @@
 			break;
 
 		case SPI_GETSCREENSAVEACTIVE:
-                    if ( GetProfileIntA( "windows", "ScreenSaveActive", 1 ) == 1 )
-                        *(BOOL16 *) lpvParam = TRUE;
+		  if(MONITOR_GetScreenSaveActive(&MONITOR_PrimaryMonitor) ||
+		     GetProfileIntA( "windows", "ScreenSaveActive", 1 ) == 1)
+   		        *(BOOL16 *) lpvParam = TRUE;
                     else
                         *(BOOL16 *) lpvParam = FALSE;
                     break;
 
 		case SPI_GETSCREENSAVETIMEOUT:
-#ifndef X_DISPLAY_MISSING
-			TSXGetScreenSaver(display, &timeout, &temp,&temp,&temp);
-#else /* X_DISPLAY_MISSING */
-			timeout = GetProfileIntA( "windows", "ScreenSaveTimeout", 300 );
-#endif /* X_DISPLAY_MISSING */
+			timeout = MONITOR_GetScreenSaveTimeout(&MONITOR_PrimaryMonitor);
+			if(!timeout)
+			    timeout = GetProfileIntA( "windows", "ScreenSaveTimeout", 300 );
 			*(INT16 *) lpvParam = timeout;
 			break;
 
@@ -1141,24 +1118,15 @@
                     break;
 
 		case SPI_SETBEEP:
-			if (uParam == TRUE)
-				keyboard_value.bell_percent = -1;
-			else
-				keyboard_value.bell_percent = 0;			
-   			TSXChangeKeyboardControl(display, KBBellPercent, 
-   							&keyboard_value);
+		        KEYBOARD_SetBeepActive(uParam);
 			break;
 
 		case SPI_SETSCREENSAVEACTIVE:
-			if (uParam == TRUE)
-				TSXActivateScreenSaver(display);
-			else
-				TSXResetScreenSaver(display);
+			MONITOR_SetScreenSaveActive(&MONITOR_PrimaryMonitor, uParam);
 			break;
 
 		case SPI_SETSCREENSAVETIMEOUT:
-			TSXSetScreenSaver(display, uParam, 60, DefaultBlanking, 
-							DefaultExposures);
+			MONITOR_SetScreenSaveTimeout(&MONITOR_PrimaryMonitor, uParam);
 			break;
 
 		case SPI_SETDESKWALLPAPER:
diff --git a/objects/bitmap.c b/objects/bitmap.c
index bb38dd3..f3d9089 100644
--- a/objects/bitmap.c
+++ b/objects/bitmap.c
@@ -20,6 +20,50 @@
 #include "monitor.h"
 #include "wine/winuser16.h"
 
+/**********************************************************************/
+
+BITMAP_DRIVER *BITMAP_Driver = NULL;
+
+/***********************************************************************
+ *           BITMAP_GetPadding
+ *
+ * Return number of bytes to pad a scanline of 16-bit aligned Windows DDB data.
+ */
+INT BITMAP_GetPadding( int bmWidth, int bpp )
+{
+    INT pad;
+
+    switch (bpp) 
+    {
+    case 1:
+        pad = ((bmWidth-1) & 8) ? 0 : 1;
+	break;
+
+    case 8:
+	pad = (2 - (bmWidth & 1)) & 1;
+	break;
+
+    case 24:
+	pad = (bmWidth*3) & 1;
+	break;
+
+    case 32:
+    case 16:
+    case 15:
+	pad = 0; /* we have 16bit alignment already */
+	break;
+
+    case 4:
+	if (!(bmWidth & 3)) pad = 0;
+	else pad = ((4 - (bmWidth & 3)) + 1) / 2;
+	break;
+
+    default:
+	WARN(bitmap,"Unknown depth %d, please report.\n", bpp );
+        return -1;
+    }
+    return pad;
+}
 
 /***********************************************************************
  *           BITMAP_GetWidthBytes
@@ -717,7 +761,7 @@
     {
         if ( count <= sizeof(BITMAP16) )
         {
-            BITMAP *bmp32 = &bmp->dib->dibSection.dsBm;
+            BITMAP *bmp32 = &bmp->dib->dsBm;
 	    BITMAP16 bmp16;
 	    bmp16.bmType       = bmp32->bmType;
 	    bmp16.bmWidth      = bmp32->bmWidth;
@@ -768,7 +812,7 @@
 	    if (count > sizeof(DIBSECTION)) count = sizeof(DIBSECTION);
 	}
 
-	memcpy( buffer, &bmp->dib->dibSection, count );
+	memcpy( buffer, bmp->dib, count );
 	return count;
     }
     else
diff --git a/objects/color.c b/objects/color.c
index 3a47a38..e074faa 100644
--- a/objects/color.c
+++ b/objects/color.c
@@ -5,85 +5,28 @@
  * Copyright 1996 Alex Korobka
  */
 
-#include "ts_xlib.h"
-#include "x11drv.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include "windef.h"
-#include "options.h"
-#include "gdi.h"
 #include "color.h"
 #include "debug.h"
-#include "xmalloc.h"
-#include "monitor.h"
+#include "palette.h"
+#include "windef.h"
 
-/* Palette indexed mode:
 
- *	logical palette -> mapping -> pixel
- *				     
- *
- * Windows needs contiguous color space ( from 0 to n ) but 
- * it is possible only with the private colormap. Otherwise we
- * have to map DC palette indices to real pixel values. With 
- * private colormaps it boils down to the identity mapping. The
- * other special case is when we have a fixed color visual with 
- * the screendepth > 8 - we abandon palette mappings altogether 
- * because pixel values can be calculated without X server 
- * assistance.
- *
- * Windows palette manager is described in the
- * http://premium.microsoft.com/msdn/library/techart/f30/f34/f40/d4d/sa942.htm
- */
-
-typedef struct
-{ 
-    Colormap    colorMap;
-    UINT16      size;
-    UINT16      flags;
-    INT	monoPlane;	 /* bit plane different for white and black pixels */
-
-    INT	(*mapColor)( DC*, COLORREF );
-} CSPACE;
-
-static CSPACE cSpace = {0, 0, 0};
-
-static int COLOR_Redshift   = 0; /* to handle abortive COLOR_VIRTUAL visuals */
-static int COLOR_Redmax     = 0;
-static int COLOR_Greenshift = 0;
-static int COLOR_Greenmax   = 0;
-static int COLOR_Blueshift  = 0;
-static int COLOR_Bluemax    = 0;
-static int COLOR_Graymax    = 0;
-
-/* System color space. 
+/***********************************************************************
+ * System color space. 
  *
  * First 10 and last 10 colors in COLOR_sysPalette are
  * "guarded". RealizePalette changes only the rest of colorcells. For
  * currently inactive window it changes only DC palette mappings.
  */
 
-#define NB_COLORCUBE_START_INDEX	63
+PALETTEENTRY *COLOR_sysPal = NULL; /* current system palette */
 
-Visual* 		visual = NULL;
+int COLOR_gapStart = 256;
+int COLOR_gapEnd = -1;
+int COLOR_gapFilled = 0;
+int COLOR_max = 256;
 
-static PALETTEENTRY* COLOR_sysPal = NULL;    /* current system palette */
-static int COLOR_gapStart = 256;
-static int COLOR_gapEnd = -1;
-static int COLOR_gapFilled = 0;
-static int COLOR_max = 256;
-
-  /* First free dynamic color cell, 0 = full palette, -1 = fixed palette */
-static int            COLOR_firstFree = 0; 
-static unsigned char  COLOR_freeList[256];
-
-  /* Maps entry in the system palette to X pixel value */
-int* COLOR_PaletteToPixel = NULL;
-
-  /* Maps pixel to the entry in the system palette */
-int* COLOR_PixelToPalette = NULL;
-
-static const PALETTEENTRY __sysPalTemplate[NB_RESERVED_COLORS] = 
+const PALETTEENTRY COLOR_sysPalTemplate[NB_RESERVED_COLORS] = 
 {
     /* first 10 entries in the system palette */
     /* red  green blue  flags */
@@ -116,573 +59,21 @@
     { 0xff, 0xff, 0xff, PC_SYS_USED }     /* last 10 */
 };
 
-   /* Map an EGA index (0..15) to a pixel value in the system color space.  */
-
-int COLOR_mapEGAPixel[16];
-
 /***********************************************************************
- *	Misc auxiliary functions
+ *           COLOR_GetSystemPaletteTemplate
  */
-Colormap X11DRV_COLOR_GetColormap(void)
-{
-    return cSpace.colorMap;
-}
-
-BOOL COLOR_GetMonoPlane(INT* plane)
-{
-    *plane = cSpace.monoPlane;
-    return (cSpace.flags & COLOR_WHITESET) ? TRUE : FALSE;
-}
-
-UINT16 COLOR_GetSystemPaletteSize(void)
-{
-    return (cSpace.flags & COLOR_PRIVATE) ? cSpace.size : 256;
-}
-
-UINT16 COLOR_GetSystemPaletteFlags(void)
-{
-    return cSpace.flags;
-}
-
 const PALETTEENTRY* COLOR_GetSystemPaletteTemplate(void)
 {
-    return __sysPalTemplate;
+    return COLOR_sysPalTemplate;
 }
 
+/***********************************************************************
+ *           COLOR_GetSystemPaletteEntry
+ */
+
 COLORREF COLOR_GetSystemPaletteEntry(UINT i)
 {
- return *(COLORREF*)(COLOR_sysPal + i) & 0x00ffffff;
-}
-
-void COLOR_FormatSystemPalette(void)
-{
- /* Build free list so we'd have an easy way to find
-  * out if there are any available colorcells. 
-  */
-
-  int i, j = COLOR_firstFree = NB_RESERVED_COLORS/2;
-
-  COLOR_sysPal[j].peFlags = 0;
-  for( i = NB_RESERVED_COLORS/2 + 1 ; i < 256 - NB_RESERVED_COLORS/2 ; i++ )
-    if( i < COLOR_gapStart || i > COLOR_gapEnd )
-      {
-	COLOR_sysPal[i].peFlags = 0;  /* unused tag */
-	COLOR_freeList[j] = i;	  /* next */
-        j = i;
-      }
-  COLOR_freeList[j] = 0;
-}
-
-BOOL COLOR_CheckSysColor(COLORREF c)
-{
-  int i;
-  for( i = 0; i < NB_RESERVED_COLORS; i++ )
-       if( c == (*(COLORREF*)(__sysPalTemplate + i) & 0x00ffffff) )
-	   return 0;
-  return 1;
-}
-
-/***********************************************************************
- *      Colormap Initialization
- */
-static void COLOR_FillDefaultColors(void)
-{
- /* initialize unused entries to what Windows uses as a color 
-  * cube - based on Greg Kreider's code. 
-  */
-
-  int i = 0, idx = 0;
-  int red, no_r, inc_r;
-  int green, no_g, inc_g; 
-  int blue, no_b, inc_b;
-  
-  if (cSpace.size <= NB_RESERVED_COLORS)
-  	return;
-  while (i*i*i < (cSpace.size - NB_RESERVED_COLORS)) i++;
-  no_r = no_g = no_b = --i;
-  if ((no_r * (no_g+1) * no_b) < (cSpace.size - NB_RESERVED_COLORS)) no_g++;
-  if ((no_r * no_g * (no_b+1)) < (cSpace.size - NB_RESERVED_COLORS)) no_b++;
-  inc_r = (255 - NB_COLORCUBE_START_INDEX)/no_r;
-  inc_g = (255 - NB_COLORCUBE_START_INDEX)/no_g;
-  inc_b = (255 - NB_COLORCUBE_START_INDEX)/no_b;
-
-  idx = COLOR_firstFree;
-
-  if( idx != -1 )
-    for (blue = NB_COLORCUBE_START_INDEX; blue < 256 && idx; blue += inc_b )
-     for (green = NB_COLORCUBE_START_INDEX; green < 256 && idx; green += inc_g )
-      for (red = NB_COLORCUBE_START_INDEX; red < 256 && idx; red += inc_r )
-      {
-	 /* weird but true */
-
-	 if( red == NB_COLORCUBE_START_INDEX && green == red && blue == green ) continue;
-
-         COLOR_sysPal[idx].peRed = red;
-         COLOR_sysPal[idx].peGreen = green;
-         COLOR_sysPal[idx].peBlue = blue;
-         
-	 /* set X color */
-
-	 if( cSpace.flags & COLOR_VIRTUAL )
-	 {
-            if (COLOR_Redmax != 255) no_r = (red * COLOR_Redmax) / 255;
-            if (COLOR_Greenmax != 255) no_g = (green * COLOR_Greenmax) / 255;
-            if (COLOR_Bluemax != 255) no_b = (blue * COLOR_Bluemax) / 255;
-
-            COLOR_PaletteToPixel[idx] = (no_r << COLOR_Redshift) | (no_g << COLOR_Greenshift) | (no_b << COLOR_Blueshift);
-	 }
-	 else if( !(cSpace.flags & COLOR_FIXED) )
-	 {
-	   XColor color = { color.pixel = (COLOR_PaletteToPixel)? COLOR_PaletteToPixel[idx] : idx ,
-	                    COLOR_sysPal[idx].peRed << 8,
-			    COLOR_sysPal[idx].peGreen << 8,
-			    COLOR_sysPal[idx].peGreen << 8,
-			    (DoRed | DoGreen | DoBlue) };
-	   TSXStoreColor(display, cSpace.colorMap, &color);
-	 }
-	 idx = COLOR_freeList[idx];
-      }
-
-  /* try to fill some entries in the "gap" with
-   * what's already in the colormap - they will be
-   * mappable to but not changeable. */
-
-  if( COLOR_gapStart < COLOR_gapEnd && COLOR_PixelToPalette )
-  {
-    XColor	xc;
-    int		r, g, b, max;
-
-    max = COLOR_max - (256 - (COLOR_gapEnd - COLOR_gapStart));
-    for ( i = 0, idx = COLOR_gapStart; i < 256 && idx <= COLOR_gapEnd; i++ )
-      if( COLOR_PixelToPalette[i] == 0 )
-	{
-	  xc.pixel = i;
-
-	  TSXQueryColor(display, cSpace.colorMap, &xc);
-	  r = xc.red>>8; g = xc.green>>8; b = xc.blue>>8;
-
-	  if( xc.pixel < 256 && COLOR_CheckSysColor(RGB(r, g, b)) &&
-	      TSXAllocColor(display, cSpace.colorMap, &xc) )
-	  {
-	     COLOR_PixelToPalette[xc.pixel] = idx;
-	     COLOR_PaletteToPixel[idx] = xc.pixel;
-           *(COLORREF*)(COLOR_sysPal + idx) = RGB(r, g, b);
-	     COLOR_sysPal[idx++].peFlags |= PC_SYS_USED;
-	     if( --max <= 0 ) break;
-	  }
-	}
-    COLOR_gapFilled = idx - COLOR_gapStart;    
-  }
-}
-
-/***********************************************************************
- *           COLOR_BuildPrivateMap/COLOR_BuildSharedMap
- *
- * Allocate colorcells and initialize mapping tables.
- */
-static BOOL COLOR_BuildPrivateMap(CSPACE* cs)
-{
-    /* Private colormap - identity mapping */
-
-    XColor color;
-    int i; 
-
-    COLOR_sysPal = (PALETTEENTRY*)xmalloc(sizeof(PALETTEENTRY)*cs->size);
-
-    TRACE(palette,"Building private map - %i palette entries\n", cs->size);
-
-      /* Allocate system palette colors */ 
-
-    for( i=0; i < cs->size; i++ )
-    {
-       if( i < NB_RESERVED_COLORS/2 )
-       {
-         color.red   = __sysPalTemplate[i].peRed * 65535 / 255;
-         color.green = __sysPalTemplate[i].peGreen * 65535 / 255;
-         color.blue  = __sysPalTemplate[i].peBlue * 65535 / 255;
-	 COLOR_sysPal[i] = __sysPalTemplate[i];
-       }
-       else if( i >= cs->size - NB_RESERVED_COLORS/2 )
-       {
-	 int j = NB_RESERVED_COLORS + i - cs->size;
-         color.red   = __sysPalTemplate[j].peRed * 65535 / 255;
-         color.green = __sysPalTemplate[j].peGreen * 65535 / 255;
-         color.blue  = __sysPalTemplate[j].peBlue * 65535 / 255;
-	 COLOR_sysPal[i] = __sysPalTemplate[j];
-       }
-
-       color.flags = DoRed | DoGreen | DoBlue;
-       color.pixel = i;
-       TSXStoreColor(display, cs->colorMap, &color);
-
-       /* Set EGA mapping if color is from the first or last eight */
-
-       if (i < 8)
-           COLOR_mapEGAPixel[i] = color.pixel;
-       else if (i >= cs->size - 8 )
-           COLOR_mapEGAPixel[i - (cs->size - 16)] = color.pixel;
-    }
-
-    COLOR_PixelToPalette = COLOR_PaletteToPixel = NULL;
-
-    COLOR_gapStart = 256; COLOR_gapEnd = -1;
-
-    COLOR_firstFree = (cs->size > NB_RESERVED_COLORS)?NB_RESERVED_COLORS/2 : -1;
-
-    return FALSE;
-}
-
-static BOOL COLOR_BuildSharedMap(CSPACE* cs)
-{
-   XColor		color;
-   unsigned long        sysPixel[NB_RESERVED_COLORS];
-   unsigned long*	pixDynMapping = NULL;
-   unsigned long	plane_masks[1];
-   int			i, j, warn = 0;
-   int			diff, r, g, b, max = 256, bp = 0, wp = 1;
-   int			step = 1;
-
-   /* read "AllocSystemColors" from wine.conf */
-
-   COLOR_max = PROFILE_GetWineIniInt( "options", "AllocSystemColors", 256);
-   if (COLOR_max > 256) COLOR_max = 256;
-   else if (COLOR_max < 20) COLOR_max = 20;
-   TRACE(palette,"%d colors configured.\n", COLOR_max);
-   
-   TRACE(palette,"Building shared map - %i palette entries\n", cs->size);
-
-   /* Be nice and allocate system colors as read-only */
-
-   for( i = 0; i < NB_RESERVED_COLORS; i++ )
-     { 
-        color.red   = __sysPalTemplate[i].peRed * 65535 / 255;
-        color.green = __sysPalTemplate[i].peGreen * 65535 / 255;
-        color.blue  = __sysPalTemplate[i].peBlue * 65535 / 255;
-        color.flags = DoRed | DoGreen | DoBlue;
-
-        if (!TSXAllocColor( display, cSpace.colorMap, &color ))
-        { 
-	     XColor	best, c;
-	     
-             if( !warn++ ) 
-	     {
-		  WARN(palette, "Not enough colors for the full system palette.\n");
-
-	          bp = BlackPixel(display, DefaultScreen(display));
-	          wp = WhitePixel(display, DefaultScreen(display));
-
-	          max = (0xffffffff)>>(32 - MONITOR_GetDepth(&MONITOR_PrimaryMonitor));
-	          if( max > 256 ) 
-	          {
-	  	      step = max/256;
-		      max = 256;
-	          }
-	     }
-
-	     /* reinit color (XAllocColor() may change it)
-	      * and map to the best shared colorcell */
-
-             color.red   = __sysPalTemplate[i].peRed * 65535 / 255;
-             color.green = __sysPalTemplate[i].peGreen * 65535 / 255;
-             color.blue  = __sysPalTemplate[i].peBlue * 65535 / 255;
-
-	     best.pixel = best.red = best.green = best.blue = 0;
-	     for( c.pixel = 0, diff = 0x7fffffff; c.pixel < max; c.pixel += step )
-	     {
-		TSXQueryColor(display, cSpace.colorMap, &c);
-		r = (c.red - color.red)>>8; 
-		g = (c.green - color.green)>>8; 
-		b = (c.blue - color.blue)>>8;
-		r = r*r + g*g + b*b;
-		if( r < diff ) { best = c; diff = r; }
-	     }
-
-	     if( TSXAllocColor(display, cSpace.colorMap, &best) )
-		 color.pixel = best.pixel;
-	     else color.pixel = (i < NB_RESERVED_COLORS/2)? bp : wp;
-        }
-
-        sysPixel[i] = color.pixel;
-
-        TRACE(palette,"syscolor(%lx) -> pixel %i\n",
-		      *(COLORREF*)(__sysPalTemplate+i), (int)color.pixel);
-
-        /* Set EGA mapping if color in the first or last eight */
-
-        if (i < 8)
-            COLOR_mapEGAPixel[i] = color.pixel;
-        else if (i >= NB_RESERVED_COLORS - 8 )
-            COLOR_mapEGAPixel[i - (NB_RESERVED_COLORS-16)] = color.pixel;
-     }
-
-   /* now allocate changeable set */
-
-   if( !(cSpace.flags & COLOR_FIXED) )  
-     {
-	int c_min = 0, c_max = cs->size, c_val;
-
-	TRACE(palette,"Dynamic colormap... \n");
-
-	/* comment this out if you want to debug palette init */
-
-	TSXGrabServer(display);
-
-	/* let's become the first client that actually follows 
-	 * X guidelines and does binary search...
-	 */
-
-	pixDynMapping = (unsigned long*)xmalloc(sizeof(long)*cs->size);
-        while( c_max - c_min > 0 )
-          {
-             c_val = (c_max + c_min)/2 + (c_max + c_min)%2;
-
-             if( !TSXAllocColorCells(display, cs->colorMap, False,
-                                   plane_masks, 0, pixDynMapping, c_val) )
-                 c_max = c_val - 1;
-             else
-               {
-                 TSXFreeColors(display, cs->colorMap, pixDynMapping, c_val, 0);
-                 c_min = c_val;
-               }
-          }
-
-	if( c_min > COLOR_max - NB_RESERVED_COLORS) 
-	    c_min = COLOR_max - NB_RESERVED_COLORS;
-
-	c_min = (c_min/2) + (c_min/2);		/* need even set for split palette */
-
-	if( c_min > 0 )
-	  if( !TSXAllocColorCells(display, cs->colorMap, False,
-                                plane_masks, 0, pixDynMapping, c_min) )
-	    {
-	      WARN(palette,"Inexplicable failure during colorcell allocation.\n");
-	      c_min = 0;
-	    }
-
-        cs->size = c_min + NB_RESERVED_COLORS;
-
-	TSXUngrabServer(display);
-
-	TRACE(palette,"adjusted size %i colorcells\n", cs->size);
-     }
-   else if( cSpace.flags & COLOR_VIRTUAL ) 
-	{
-          /* virtual colorspace - ToPhysical takes care of 
-           * color translations but we have to allocate full palette 
-	   * to maintain compatibility
-	   */
-	  cs->size = 256;
-	  TRACE(palette,"Virtual colorspace - screendepth %i\n", MONITOR_GetDepth(&MONITOR_PrimaryMonitor));
-	}
-   else cs->size = NB_RESERVED_COLORS;	/* system palette only - however we can alloc a bunch
-			                 * of colors and map to them */
-
-   TRACE(palette,"Shared system palette uses %i colors.\n", cs->size);
-
-   /* set gap to account for pixel shortage. It has to be right in the center
-    * of the system palette because otherwise raster ops get screwed. */
-
-   if( cs->size >= 256 )
-     { COLOR_gapStart = 256; COLOR_gapEnd = -1; }
-   else
-     { COLOR_gapStart = cs->size/2; COLOR_gapEnd = 255 - cs->size/2; }
-
-   COLOR_firstFree = ( cs->size > NB_RESERVED_COLORS && 
-		      (cs->flags & COLOR_VIRTUAL || !(cs->flags & COLOR_FIXED)) ) 
-		     ? NB_RESERVED_COLORS/2 : -1;
-
-   COLOR_sysPal = (PALETTEENTRY*)xmalloc(sizeof(PALETTEENTRY)*256);
-
-   /* setup system palette entry <-> pixel mappings and fill in 20 fixed entries */
-
-   if( MONITOR_GetDepth(&MONITOR_PrimaryMonitor) <= 8 )
-     {
-       COLOR_PixelToPalette = (int*)xmalloc(sizeof(int)*256);
-       memset( COLOR_PixelToPalette, 0, 256*sizeof(int) );
-     }
-
-   /* for hicolor visuals PaletteToPixel mapping is used to skip
-    * RGB->pixel calculation in COLOR_ToPhysical(). 
-    */
-
-   COLOR_PaletteToPixel = (int*)xmalloc(sizeof(int)*256);
-
-   for( i = j = 0; i < 256; i++ )
-   {
-      if( i >= COLOR_gapStart && i <= COLOR_gapEnd ) 
-      {
-         COLOR_PaletteToPixel[i] = 0;
-         COLOR_sysPal[i].peFlags = 0;	/* mark as unused */
-         continue;
-      }
-
-      if( i < NB_RESERVED_COLORS/2 )
-      {
-        COLOR_PaletteToPixel[i] = sysPixel[i];
-        COLOR_sysPal[i] = __sysPalTemplate[i];
-      }
-      else if( i >= 256 - NB_RESERVED_COLORS/2 )
-      {
-        COLOR_PaletteToPixel[i] = sysPixel[(i + NB_RESERVED_COLORS) - 256]; 
-        COLOR_sysPal[i] = __sysPalTemplate[(i + NB_RESERVED_COLORS) - 256];
-      }
-      else if( pixDynMapping )
-             COLOR_PaletteToPixel[i] = pixDynMapping[j++];
-           else
-             COLOR_PaletteToPixel[i] = i;
-
-      TRACE(palette,"index %i -> pixel %i\n", i, COLOR_PaletteToPixel[i]);
-
-      if( COLOR_PixelToPalette )
-          COLOR_PixelToPalette[COLOR_PaletteToPixel[i]] = i;
-   }
-
-   if( pixDynMapping ) free(pixDynMapping);
-
-   return TRUE;
-}
-
-/***********************************************************************
- *	     COLOR_Computeshifts
- *
- * Calculate conversion parameters for direct mapped visuals
- */
-static void COLOR_Computeshifts(unsigned long maskbits, int *shift, int *max)
-{
-    int i;
-
-    if (maskbits==0)
-    {
-        *shift=0;
-        *max=0;
-        return;
-    }
-
-    for(i=0;!(maskbits&1);i++)
-        maskbits >>= 1;
-
-    *shift = i;
-    *max = maskbits;
-}
-
-
-/***********************************************************************
- *           COLOR_Init
- *
- * Initialize color management.
- */
-BOOL COLOR_Init(void)
-{
-    int	mask, white, black;
-
-    visual = DefaultVisual( display, DefaultScreen(display) );
-
-    TRACE(palette,"initializing palette manager...\n");
-
-    white = WhitePixelOfScreen( X11DRV_GetXScreen() );
-    black = BlackPixelOfScreen( X11DRV_GetXScreen() );
-    cSpace.monoPlane = 1;
-    for( mask = 1; !((white & mask)^(black & mask)); mask <<= 1 )
-	 cSpace.monoPlane++;
-    cSpace.flags = (white & mask) ? COLOR_WHITESET : 0;
-    cSpace.size = visual->map_entries;
-
-    switch(visual->class)
-    {
-    case DirectColor:
-	cSpace.flags |= COLOR_VIRTUAL;
-    case GrayScale:
-    case PseudoColor:
-	if (Options.usePrivateMap)
-	{
-	    XSetWindowAttributes win_attr;
-
-	    cSpace.colorMap = TSXCreateColormap( display, X11DRV_GetXRootWindow(),
-						 visual, AllocAll );
-	    if (cSpace.colorMap)
-	    {
-	        cSpace.flags |= (COLOR_PRIVATE | COLOR_WHITESET);
-
-		cSpace.monoPlane = 1;
-		for( white = cSpace.size - 1; !(white & 1); white >>= 1 )
-		     cSpace.monoPlane++;
-
-	        if( X11DRV_GetXRootWindow() != DefaultRootWindow(display) )
-	        {
-		    win_attr.colormap = cSpace.colorMap;
-		    TSXChangeWindowAttributes( display, X11DRV_GetXRootWindow(),
-					 CWColormap, &win_attr );
-		}
-		break;
-	    }
-	}
-	cSpace.colorMap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
-        break;
-
-    case StaticGray:
-	cSpace.colorMap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
-	cSpace.flags |= COLOR_FIXED;
-        COLOR_Graymax = (1<<MONITOR_GetDepth(&MONITOR_PrimaryMonitor))-1;
-        break;
-
-    case TrueColor:
-	cSpace.flags |= COLOR_VIRTUAL;
-    case StaticColor: {
-    	int *depths,nrofdepths;
-	/* FIXME: hack to detect XFree32 XF_VGA16 ... We just have
-	 * depths 1 and 4
-	 */
-	depths=TSXListDepths(display,DefaultScreen(display),&nrofdepths);
-	if ((nrofdepths==2) && ((depths[0]==4) || depths[1]==4)) {
-	    cSpace.monoPlane = 1;
-	    for( white = cSpace.size - 1; !(white & 1); white >>= 1 )
-	        cSpace.monoPlane++;
-    	    cSpace.flags = (white & mask) ? COLOR_WHITESET : 0;
-	    cSpace.colorMap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
-	    TSXFree(depths);
-	    break;
-	}
-	TSXFree(depths);
-        cSpace.colorMap = DefaultColormapOfScreen( X11DRV_GetXScreen() );
-        cSpace.flags |= COLOR_FIXED;
-        COLOR_Computeshifts(visual->red_mask, &COLOR_Redshift, &COLOR_Redmax);
-        COLOR_Computeshifts(visual->green_mask, &COLOR_Greenshift, &COLOR_Greenmax);
-        COLOR_Computeshifts(visual->blue_mask, &COLOR_Blueshift, &COLOR_Bluemax);
-	break;
-    }
-    }
-
-    TRACE(palette," visual class %i (%i)\n", 
-		    visual->class, cSpace.monoPlane);
-
-    memset(COLOR_freeList, 0, 256*sizeof(unsigned char));
-
-    if (cSpace.flags & COLOR_PRIVATE)
-        COLOR_BuildPrivateMap( &cSpace );
-    else
-        COLOR_BuildSharedMap( &cSpace );
-
-    /* Build free list */
-
-    if( COLOR_firstFree != -1 )
-        COLOR_FormatSystemPalette();
-
-    COLOR_FillDefaultColors();
-
-    return TRUE;
-}
-
-/***********************************************************************
- *           COLOR_Cleanup
- *
- * Free external colors we grabbed in the FillDefaultPalette()
- */
-void COLOR_Cleanup(void)
-{
-  if( COLOR_gapFilled )
-      TSXFreeColors(display, cSpace.colorMap, 
-		  (unsigned long*)(COLOR_PaletteToPixel + COLOR_gapStart), 
-		  COLOR_gapFilled, 0);
+    return *(COLORREF*)(COLOR_sysPal + i) & 0x00ffffff;
 }
 
 /***********************************************************************
@@ -709,7 +100,6 @@
     return FALSE;
 }
 
-
 /***********************************************************************
  *	     COLOR_PaletteLookupPixel
  */
@@ -737,35 +127,6 @@
 }
 
 /***********************************************************************
- *           COLOR_LookupSystemPixel
- */
-int COLOR_LookupSystemPixel(COLORREF col)
-{
- int            i, best = 0, diff = 0x7fffffff;
- int            size = COLOR_GetSystemPaletteSize();
- int            r,g,b;
-
- for( i = 0; i < size && diff ; i++ )
-    {
-      if( i == NB_RESERVED_COLORS/2 )
-      {
-      	int newi = size - NB_RESERVED_COLORS/2;
-	if (newi>i) i=newi;
-      }
-
-      r = COLOR_sysPal[i].peRed - GetRValue(col);
-      g = COLOR_sysPal[i].peGreen - GetGValue(col);
-      b = COLOR_sysPal[i].peBlue - GetBValue(col);
-
-      r = r*r + g*g + b*b;
-
-      if( r < diff ) { best = i; diff = r; }
-    }
- 
- return (COLOR_PaletteToPixel)? COLOR_PaletteToPixel[best] : best;
-}
-
-/***********************************************************************
  *	     COLOR_PaletteLookupExactIndex
  */
 int COLOR_PaletteLookupExactIndex( PALETTEENTRY* palPalEntry, int size,
@@ -812,282 +173,3 @@
   return (0x00ffffff & *(COLORREF*)
          (COLOR_sysPal + COLOR_PaletteLookupPixel(COLOR_sysPal, 256, NULL, color, FALSE)));
 }
-
-/***********************************************************************
- *           COLOR_ToLogical
- *
- * Return RGB color for given X pixel.
- */
-COLORREF COLOR_ToLogical(int pixel)
-{
-    XColor color;
-
-#if 0
-    /* truecolor visual */
-
-    if (MONITOR_GetDepth(&MONITOR_PrimaryMonitor) >= 24) return pixel;
-#endif
-
-    /* check for hicolor visuals first */
-
-    if ( cSpace.flags & COLOR_FIXED && !COLOR_Graymax )
-    {
-         color.red = (pixel >> COLOR_Redshift) & COLOR_Redmax;
-         color.green = (pixel >> COLOR_Greenshift) & COLOR_Greenmax;
-         color.blue = (pixel >> COLOR_Blueshift) & COLOR_Bluemax;
-         return RGB((color.red * 255)/COLOR_Redmax,
-                    (color.green * 255)/COLOR_Greenmax,
-                    (color.blue * 255)/COLOR_Bluemax);
-    }
-
-    /* check if we can bypass X */
-
-    if ((MONITOR_GetDepth(&MONITOR_PrimaryMonitor) <= 8) && (pixel < 256) && 
-       !(cSpace.flags & (COLOR_VIRTUAL | COLOR_FIXED)) )
-         return  ( *(COLORREF*)(COLOR_sysPal + 
-		   ((COLOR_PixelToPalette)?COLOR_PixelToPalette[pixel]:pixel)) ) & 0x00ffffff;
-
-    color.pixel = pixel;
-    TSXQueryColor(display, cSpace.colorMap, &color);
-    return RGB(color.red >> 8, color.green >> 8, color.blue >> 8);
-}
-
-
-/***********************************************************************
- *           COLOR_ToPhysical
- *
- * Return the physical color closest to 'color'.
- */
-int COLOR_ToPhysical( DC *dc, COLORREF color )
-{
-    WORD 		 index = 0;
-    HPALETTE16		 hPal = (dc)? dc->w.hPalette: STOCK_DEFAULT_PALETTE;
-    unsigned char	 spec_type = color >> 24;
-    PALETTEOBJ* 	 palPtr = (PALETTEOBJ *) GDI_GetObjPtr( hPal, PALETTE_MAGIC );
-
-    if ( cSpace.flags & COLOR_FIXED )
-    {
-        /* there is no colormap limitation; we are going to have to compute
-         * the pixel value from the visual information stored earlier 
-	 */
-
-	unsigned 	long red, green, blue;
-	unsigned 	idx = 0;
-
-	switch(spec_type)
-        {
-          case 2: /* PALETTERGB - not sure if we really need to search palette */
-	
-	    idx = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry,
-					    palPtr->logpalette.palNumEntries,
-					    NULL, color, FALSE);
-
-            if( palPtr->mapping )
-	    {
-	        GDI_HEAP_UNLOCK( hPal );
-		return palPtr->mapping[idx];
-	    }
-
-	    color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
-	    break;
-
-          case 1: /* PALETTEINDEX */
-
-            if( (idx = color & 0xffff) >= palPtr->logpalette.palNumEntries)
-            {
-                WARN(palette, "RGB(%lx) : idx %d is out of bounds, assuming black\n", color, idx);
-		GDI_HEAP_UNLOCK( hPal );
-                return 0;
-            }
-
-            if( palPtr->mapping ) 
-	    {
-		GDI_HEAP_UNLOCK( hPal );
-		return palPtr->mapping[idx];
-	    }
-	    color = *(COLORREF*)(palPtr->logpalette.palPalEntry + idx);
-	    break;
-
-	  default:
-	    color &= 0xffffff;
-	    /* fall through to RGB */
-
-	  case 0: /* RGB */
-	    if( dc && (dc->w.bitsPerPixel == 1) )
-	    {
-		GDI_HEAP_UNLOCK( hPal );
-		return (((color >> 16) & 0xff) +
-			((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
-	    }
-
-	}
-
-        red = GetRValue(color); green = GetGValue(color); blue = GetBValue(color);
-
-	if (COLOR_Graymax)
-        {
-	    /* grayscale only; return scaled value */
-	    GDI_HEAP_UNLOCK( hPal );
-            return ( (red * 30 + green * 69 + blue * 11) * COLOR_Graymax) / 25500;
-	}
-	else
-        {
-	    /* scale each individually and construct the TrueColor pixel value */
-	    if (COLOR_Redmax != 255) red = (red * COLOR_Redmax) / 255;
-            if (COLOR_Greenmax != 255) green = (green * COLOR_Greenmax) / 255;
-	    if (COLOR_Bluemax != 255) blue = (blue * COLOR_Bluemax) / 255;
-
-	    GDI_HEAP_UNLOCK( hPal );
-	    return (red << COLOR_Redshift) | (green << COLOR_Greenshift) | (blue << COLOR_Blueshift);
-        }
-    }
-    else 
-    {
-
-	/* palPtr can be NULL when DC is being destroyed */
-
-	if( !palPtr ) return 0;
-	else if( !palPtr->mapping ) 
-            WARN(palette, "Palette %04x is not realized\n", dc->w.hPalette);
-
-	switch(spec_type)	/* we have to peruse DC and system palette */
-    	{
-	    default:
-		color &= 0xffffff;
-		/* fall through to RGB */
-
-       	    case 0:  /* RGB */
-		if( dc && (dc->w.bitsPerPixel == 1) )
-		{
-		    GDI_HEAP_UNLOCK( hPal );
-		    return (((color >> 16) & 0xff) +
-			    ((color >> 8) & 0xff) + (color & 0xff) > 255*3/2) ? 1 : 0;
-		}
-
-	    	index = COLOR_PaletteLookupPixel( COLOR_sysPal, 256, 
-						  COLOR_PaletteToPixel, color, FALSE);
-
-		/* TRACE(palette,"RGB(%lx) -> pixel %i\n", color, index);
-		 */
-	    	break;
-       	    case 1:  /* PALETTEINDEX */
-		index = color & 0xffff;
-
-	        if( index >= palPtr->logpalette.palNumEntries )
-		    WARN(palette, "RGB(%lx) : index %i is out of bounds\n", color, index); 
-		else if( palPtr->mapping ) index = palPtr->mapping[index];
-
-		/*  TRACE(palette,"PALETTEINDEX(%04x) -> pixel %i\n", (WORD)color, index);
-		 */
-		break;
-            case 2:  /* PALETTERGB */
-		index = COLOR_PaletteLookupPixel( palPtr->logpalette.palPalEntry, 
-                                             palPtr->logpalette.palNumEntries,
-                                             palPtr->mapping, color, FALSE);
-		/* TRACE(palette,"PALETTERGB(%lx) -> pixel %i\n", color, index);
-		 */
-		break;
-	}
-    }
-
-    GDI_HEAP_UNLOCK( hPal );
-    return index;
-}
-
-/***********************************************************************
- *           COLOR_SetMapping
- *
- * Set the color-mapping table for selected palette. 
- * Return number of entries which mapping has changed.
- */
-int COLOR_SetMapping( PALETTEOBJ* palPtr, UINT uStart, UINT uNum, BOOL mapOnly )
-{
-    char flag;
-    int  prevMapping = (palPtr->mapping) ? 1 : 0;
-    int  index, iRemapped = 0;
-
-    /* reset dynamic system palette entries */
-
-    if( !mapOnly && COLOR_firstFree != -1)
-         COLOR_FormatSystemPalette();
-
-    /* initialize palette mapping table */
- 
-    palPtr->mapping = (int*)xrealloc(palPtr->mapping, sizeof(int)*
-                                     palPtr->logpalette.palNumEntries);
-
-    for( uNum += uStart; uStart < uNum; uStart++ )
-    {
-        index = -1;
-        flag = PC_SYS_USED;
-
-        switch( palPtr->logpalette.palPalEntry[uStart].peFlags & 0x07 )
-        {
-	case PC_EXPLICIT:   /* palette entries are indices into system palette */
-            index = *(WORD*)(palPtr->logpalette.palPalEntry + uStart);
-            if( index > 255 || (index >= COLOR_gapStart && index <= COLOR_gapEnd) ) 
-            {
-                WARN(palette,"PC_EXPLICIT: idx %d out of system palette, assuming black.\n", index); 
-                index = 0;
-            }
-            break;
-
-	case PC_RESERVED:   /* forbid future mappings to this entry */
-            flag |= PC_SYS_RESERVED;
-
-            /* fall through */
-	default:	    /* try to collapse identical colors */
-            index = COLOR_PaletteLookupExactIndex(COLOR_sysPal, 256,  
-                             *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
-            /* fall through */
-	case PC_NOCOLLAPSE: 
-            if( index < 0 )
-            {
-                if( COLOR_firstFree > 0 && !(cSpace.flags & COLOR_FIXED) )
-                {
-                    XColor color;
-                    index = COLOR_firstFree;  /* ought to be available */
-                    COLOR_firstFree = COLOR_freeList[index];
-
-                    color.pixel = (COLOR_PaletteToPixel) ? COLOR_PaletteToPixel[index] : index;
-                    color.red = palPtr->logpalette.palPalEntry[uStart].peRed << 8;
-                    color.green = palPtr->logpalette.palPalEntry[uStart].peGreen << 8;
-                    color.blue = palPtr->logpalette.palPalEntry[uStart].peBlue << 8;
-                    color.flags = DoRed | DoGreen | DoBlue;
-                    TSXStoreColor(display, cSpace.colorMap, &color);
-
-                    COLOR_sysPal[index] = palPtr->logpalette.palPalEntry[uStart];
-                    COLOR_sysPal[index].peFlags = flag;
-		    COLOR_freeList[index] = 0;
-
-                    if( COLOR_PaletteToPixel ) index = COLOR_PaletteToPixel[index];
-                    break;
-                }
-                else if ( cSpace.flags & COLOR_VIRTUAL ) 
-                {
-                    index = COLOR_ToPhysical( NULL, 0x00ffffff &
-                             *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart));
-                    break;     
-                }
-
-                /* we have to map to existing entry in the system palette */
-
-                index = COLOR_PaletteLookupPixel(COLOR_sysPal, 256, NULL, 
-                       *(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), TRUE);
-            }
-	    palPtr->logpalette.palPalEntry[uStart].peFlags |= PC_SYS_USED;
-
-            if( COLOR_PaletteToPixel ) index = COLOR_PaletteToPixel[index];
-            break;
-        }
-
-        if( !prevMapping || palPtr->mapping[uStart] != index ) iRemapped++;
-        palPtr->mapping[uStart] = index;
-
-        TRACE(palette,"entry %i (%lx) -> pixel %i\n", uStart, 
-				*(COLORREF*)(palPtr->logpalette.palPalEntry + uStart), index);
-	
-    }
-    return iRemapped;
-}
-
diff --git a/objects/cursoricon.c b/objects/cursoricon.c
index a9d21d6..c1b70af 100644
--- a/objects/cursoricon.c
+++ b/objects/cursoricon.c
@@ -31,7 +31,9 @@
 
 #include <string.h>
 #include <stdlib.h>
+
 #include "wine/winbase16.h"
+#include "wine/winuser16.h"
 #include "heap.h"
 #include "color.h"
 #include "bitmap.h"
@@ -827,7 +829,6 @@
            unsigned xor_width, and_width, val_base = 0xffffffff >> (32 - bpp);
            BYTE* pbc = NULL;
 
-           COLORREF       col;
            CURSORICONINFO cI;
 
 	   TRACE(icon, "[%04x] %ix%i %ibpp (bogus %ibps)\n", 
@@ -867,8 +868,7 @@
 
 		  unsigned *psc = (unsigned*)(psPtr + (ix * bpp)/8);
                   unsigned  val = ((*psc) >> (ix * bpp)%8) & val_base;
-                  col = COLOR_ToLogical(val);
-		  if( (GetRValue(col) + GetGValue(col) + GetBValue(col)) > 0x180 )
+		  if(!PALETTE_Driver->pIsDark(val))
                   {
                     pbc = pxbPtr + ix/8;
                    *pbc |= 0x80 >> (ix%8);
diff --git a/objects/dc.c b/objects/dc.c
index 32984b0..fc10681 100644
--- a/objects/dc.c
+++ b/objects/dc.c
@@ -5,8 +5,10 @@
  *
  */
 
+#ifndef X_DISPLAY_MISSING
 #include "ts_xlib.h"
 #include "x11drv.h"
+#endif  /* !defined(X_DISPLAY_MISSING) */
 
 #include <stdlib.h>
 #include <string.h>
@@ -856,21 +858,27 @@
 BOOL WINAPI GetDCOrgEx( HDC hDC, LPPOINT lpp )
 {
     DC * dc;
-    X11DRV_PDEVICE *physDev;
 
     if (!lpp) return FALSE;
     if (!(dc = (DC *) GDI_GetObjPtr( hDC, DC_MAGIC ))) return FALSE;
-    physDev = (X11DRV_PDEVICE *)dc->physDev;
 
+#ifndef X_DISPLAY_MISSING
     if (!(dc->w.flags & DC_MEMORY))
     {
+       X11DRV_PDEVICE *physDev;
        Window root;
        int w, h, border, depth;
+
+       physDev = (X11DRV_PDEVICE *) dc->physDev;
+
        /* FIXME: this is not correct for managed windows */
        TSXGetGeometry( display, physDev->drawable, &root,
                     (int*)&lpp->x, (int*)&lpp->y, &w, &h, &border, &depth );
     }
-    else lpp->x = lpp->y = 0;
+    else 
+#endif  /* !defined(X_DISPLAY_MISSING) */
+      lpp->x = lpp->y = 0;
+
     lpp->x += dc->w.DCOrgX; lpp->y += dc->w.DCOrgY;
     GDI_HEAP_UNLOCK( hDC );
     return TRUE;
diff --git a/objects/dib.c b/objects/dib.c
index 14eea81..917b849 100644
--- a/objects/dib.c
+++ b/objects/dib.c
@@ -3,24 +3,14 @@
  *
  * Copyright 1993,1994  Alexandre Julliard
  *
- * TODO: Still contains some references to X11DRV.
  */
 
-#include "ts_xlib.h"
-#include "x11drv.h"
-
-#include <stdlib.h>
-#include "dc.h"
 #include "bitmap.h"
 #include "callback.h"
-#include "palette.h"
-#include "global.h"
-#include "selectors.h"
+#include "dc.h"
 #include "debug.h"
-#include "local.h"
-#include "xmalloc.h" /* for XCREATEIMAGE macro */
 #include "monitor.h"
-
+#include "palette.h"
 
 /***********************************************************************
  *           DIB_GetDIBWidthBytes
@@ -187,86 +177,34 @@
  *    Failure: 0
  */
 INT WINAPI SetDIBits( HDC hdc, HBITMAP hbitmap, UINT startscan,
-                          UINT lines, LPCVOID bits, const BITMAPINFO *info,
-                          UINT coloruse )
+		      UINT lines, LPCVOID bits, const BITMAPINFO *info,
+		      UINT coloruse )
 {
-    DIB_SETIMAGEBITS_DESCR descr;
-    BITMAPOBJ * bmp;
-    int height, tmpheight;
+    DC *dc;
+    BITMAPOBJ *bitmap;
     INT result;
 
-      /* Check parameters */
-
-    descr.dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
-    if (!descr.dc) 
+    /* Check parameters */
+    dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC );
+    if (!dc) 
     {
-	descr.dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
-	if (!descr.dc) return 0;
+	dc = (DC *) GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
+	if (!dc) return 0;
     }
-    if (!(bmp = (BITMAPOBJ *)GDI_GetObjPtr( hbitmap, BITMAP_MAGIC )))
+
+    if (!(bitmap = (BITMAPOBJ *) GDI_GetObjPtr( hbitmap, BITMAP_MAGIC )))
     {
         GDI_HEAP_UNLOCK( hdc );
         return 0;
     }
-    if (DIB_GetBitmapInfo( &info->bmiHeader, &descr.infoWidth, &height,
-                           &descr.infoBpp, &descr.compression ) == -1)
-    {
-        GDI_HEAP_UNLOCK( hbitmap );
-        GDI_HEAP_UNLOCK( hdc );
-        return 0;
-    }
-    tmpheight = height;
-    if (height < 0) height = -height;
-    if (!lines || (startscan >= height))
-    {
-        GDI_HEAP_UNLOCK( hbitmap );
-        GDI_HEAP_UNLOCK( hdc );
-        return 0;
-    }
-    if (startscan + lines > height) lines = height - startscan;
 
-    if (descr.infoBpp <= 8)
-    {
-        descr.colorMap = X11DRV_DIB_BuildColorMap( descr.dc, coloruse,
-						   bmp->bitmap.bmBitsPixel,
-						   info, &descr.nColorMap );
-        if (!descr.colorMap)
-        {
-            GDI_HEAP_UNLOCK( hbitmap );
-            GDI_HEAP_UNLOCK( hdc );
-            return 0;
-        } 
-    } else
-    	descr.colorMap = 0;
-
-    /* HACK for now */
-    if(!bmp->DDBitmap)
-        X11DRV_CreateBitmap(hbitmap);
-{
-    X11DRV_PHYSBITMAP *pbitmap = bmp->DDBitmap->physBitmap;
-
-
-    descr.bits      = bits;
-    descr.image     = NULL;
-    descr.lines     = tmpheight >= 0 ? lines : -lines;
-    descr.depth     = bmp->bitmap.bmBitsPixel;
-    descr.drawable  = pbitmap->pixmap;
-    descr.gc        = BITMAP_GC(bmp);
-    descr.xSrc      = 0;
-    descr.ySrc      = 0;
-    descr.xDest     = 0;
-    descr.yDest     = height - startscan - lines;
-    descr.width     = bmp->bitmap.bmWidth;
-    descr.height    = lines;
-}
-    EnterCriticalSection( &X11DRV_CritSection );
-    result = CALL_LARGE_STACK( X11DRV_DIB_SetImageBits, &descr );
-    LeaveCriticalSection( &X11DRV_CritSection );
-
-    if (descr.colorMap) HeapFree(GetProcessHeap(), 0, descr.colorMap);
+    result = BITMAP_Driver->pSetDIBits(bitmap, dc, startscan, 
+				       lines, bits, info, 
+				       coloruse, hbitmap);
 
     GDI_HEAP_UNLOCK( hdc );
     GDI_HEAP_UNLOCK( hbitmap );
+
     return result;
 }
 
@@ -466,34 +404,6 @@
     { 0xff, 0xff, 0xff, 0x00 }
 };
 
-/*********************************************************************
- *         DIB_GetNearestIndex
- *
- * Helper for GetDIBits.
- * Returns the nearest colour table index for a given RGB.
- * Nearest is defined by minimizing the sum of the squares.
- */
-static INT DIB_GetNearestIndex(BITMAPINFO *info, BYTE r, BYTE g, BYTE b)
-{
-    INT i, best = -1, diff, bestdiff = -1;
-    RGBQUAD *color;
-
-    for(color = info->bmiColors, i = 0; i < (1 << info->bmiHeader.biBitCount);
-	color++, i++) {
-        diff = (r - color->rgbRed) * (r - color->rgbRed) +
-	       (g - color->rgbGreen) * (g - color->rgbGreen) +
-	       (b - color->rgbBlue) * (b - color->rgbBlue);
-	if(diff == 0)
-	    return i;
-	if(best == -1 || diff < bestdiff) {
-	    best = i;
-	    bestdiff = diff;
-	}
-    }
-    return best;
-}
-
-
 /***********************************************************************
  *           GetDIBits16    (GDI.441)
  */
@@ -527,8 +437,7 @@
     BITMAPOBJ * bmp;
     PALETTEENTRY * palEntry;
     PALETTEOBJ * palette;
-    XImage * bmpImage;
-    int i, x, y;
+    int i;
 
     if (!lines) return 0;
     if (!info) return 0;
@@ -539,9 +448,13 @@
 	if (!dc) return 0;
     }
     if (!(bmp = (BITMAPOBJ *)GDI_GetObjPtr( hbitmap, BITMAP_MAGIC )))
+    {
+        GDI_HEAP_UNLOCK( hdc );
 	return 0;
+    }
     if (!(palette = (PALETTEOBJ*)GDI_GetObjPtr( dc->w.hPalette, PALETTE_MAGIC )))
     {
+        GDI_HEAP_UNLOCK( hdc );
         GDI_HEAP_UNLOCK( hbitmap );
         return 0;
     }
@@ -602,379 +515,17 @@
 	}
     }
 
+    GDI_HEAP_UNLOCK( dc->w.hPalette );
+
     if (bits)
-    {	
-	BYTE    *bbits = (BYTE*)bits, *linestart;
-	int	dstwidth, yend, xend = bmp->bitmap.bmWidth;
-
-        TRACE(bitmap, "%u scanlines of (%i,%i) -> (%i,%i) starting from %u\n",
-	      lines, bmp->bitmap.bmWidth, bmp->bitmap.bmHeight,
-	      (int)info->bmiHeader.biWidth, (int)info->bmiHeader.biHeight,
-	      startscan );
-
-	/* adjust number of scanlines to copy */
-
-	if( lines > info->bmiHeader.biHeight )
-	    lines = info->bmiHeader.biHeight;
-
-	yend = startscan + lines;
-	if( startscan >= bmp->bitmap.bmHeight ) 
+    {
+	if(!BITMAP_Driver->pGetDIBits(bmp, dc, startscan, lines, bits, info, coloruse, hbitmap))	
         {
-            GDI_HEAP_UNLOCK( hbitmap );
-            GDI_HEAP_UNLOCK( dc->w.hPalette );
-            return FALSE;
-        }
-	if( yend > bmp->bitmap.bmHeight ) yend = bmp->bitmap.bmHeight;
+	    GDI_HEAP_UNLOCK( hdc );
+	    GDI_HEAP_UNLOCK( hbitmap );
 
-	/* adjust scanline width */
-
-	if(bmp->bitmap.bmWidth > info->bmiHeader.biWidth)
-            xend = info->bmiHeader.biWidth;
-
-	/* HACK for now */
-	if(!bmp->DDBitmap)
-	    X11DRV_CreateBitmap(hbitmap);
-
-	dstwidth = DIB_GetDIBWidthBytes( info->bmiHeader.biWidth,
-					 info->bmiHeader.biBitCount );
-
-        EnterCriticalSection( &X11DRV_CritSection );
-	bmpImage = (XImage *)CALL_LARGE_STACK( X11DRV_BITMAP_GetXImage, bmp );
-
-	linestart = bbits;
-	switch( info->bmiHeader.biBitCount ) {
-
-	case 1: /* 1 bit DIB */
-	    {
-	        unsigned long white = (1 << bmp->bitmap.bmBitsPixel) - 1;
-
-		for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        if (!(x&7)) *bbits = 0;
-			*bbits |= (XGetPixel( bmpImage, x, y) >= white) 
-			  << (7 - (x&7));
-			if ((x&7)==7) bbits++;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-	    }
-	    break;
-
-
-	case 4: /* 4 bit DIB */
-	    switch(bmp->bitmap.bmBitsPixel) {
-
-	    case 1: /* 1/4 bit bmp -> 4 bit DIB */
-	    case 4:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        if (!(x&1)) *bbits = 0;
-			*bbits |= XGetPixel( bmpImage, x, y)<<(4*(1-(x&1)));
-			if ((x&1)==1) bbits++;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 8: /* 8 bit bmp -> 4 bit DIB */
-	        palEntry = palette->logpalette.palPalEntry;
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel = XGetPixel( bmpImage, x, y );
-			if (!(x&1)) *bbits = 0;
-			*bbits |= ( DIB_GetNearestIndex(info,
-				    palEntry[pixel].peRed,
-				    palEntry[pixel].peGreen,
-				    palEntry[pixel].peBlue )
-					  << (4*(1-(x&1))) );
-			if ((x&1)==1) bbits++;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 15: /* 15/16 bit bmp -> 4 bit DIB */
-	    case 16:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel = XGetPixel( bmpImage, x, y );
-			if (!(x&1)) *bbits = 0;
-			*bbits |= ( DIB_GetNearestIndex(info,
-				     ((pixel << 3) & 0xf8) |
-				     ((pixel >> 2) &  0x7),
-				     ((pixel >> 2) & 0xf8) |
-				     ((pixel >> 7) & 0x7),
-				     ((pixel >> 7) & 0xf8) |
-				     ((pixel >> 12) & 0x7) ) 
-					  << (4*(1-(x&1))) );
-			if ((x&1)==1) bbits++;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 24: /* 24/32 bit bmp -> 4 bit DIB */
-	    case 32:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel = XGetPixel( bmpImage, x, y );
-			if (!(x&1)) *bbits = 0;
-			*bbits |= ( DIB_GetNearestIndex( info,
-				     (pixel >> 16) & 0xff,
-				     (pixel >>  8) & 0xff,
-				      pixel & 0xff )
-					  << (4*(1-(x&1))) );
-			if ((x&1)==1) bbits++;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    default: /* ? bit bmp -> 4 bit DIB */
-	        FIXME(bitmap, "4 bit DIB %d bit bitmap\n",
-				  bmp->bitmap.bmBitsPixel);
-		break;
-	    }
-	    break;
-
-
-	case 8: /* 8 bit DIB */
-	    switch(bmp->bitmap.bmBitsPixel) {
-
-	    case 1: /* 1/4/8 bit bmp -> 8 bit DIB */
-	    case 4:
-	    case 8:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ )
-		        *bbits++ = XGetPixel( bmpImage, x, y );
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 15: /* 15/16 bit bmp -> 8 bit DIB */
-	    case 16:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel = XGetPixel( bmpImage, x, y );
-		        *bbits++ = DIB_GetNearestIndex( info, 
-					 ((pixel << 3) & 0xf8) |
-					 ((pixel >> 2) &  0x7),
-					 ((pixel >> 2) & 0xf8) |
-					 ((pixel >> 7) & 0x7),
-					 ((pixel >> 7) & 0xf8) |
-					 ((pixel >> 12) & 0x7) );
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 24: /* 24/32 bit bmp -> 8 bit DIB */
-	    case 32:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel = XGetPixel( bmpImage, x, y );
-		        *bbits++ = DIB_GetNearestIndex( info,
-					 (pixel >> 16) & 0xff,
-					 (pixel >>  8) & 0xff,
-					  pixel & 0xff );
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    default: /* ? bit bmp -> 8 bit DIB */
-	        FIXME(bitmap, "8 bit DIB %d bit bitmap\n",
-				  bmp->bitmap.bmBitsPixel);
-		break;
-	    }
-	    break;
-
-
-	case 15: /* 15/16 bit DIB */
-	case 16:
-	    switch(bmp->bitmap.bmBitsPixel) {
-
-	    case 15: /* 15/16 bit bmp -> 16 bit DIB */
-	    case 16:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = pixel & 0xff;
-			*bbits++ = (pixel >> 8) & 0xff;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-		   
-	    case 24: /* 24/32 bit bmp -> 16 bit DIB */
-	    case 32:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = ((pixel >> 6) & 0xe0) |
-			           ((pixel >> 3) & 0x1f);
-			*bbits++ = ((pixel >> 17) & 0x7c) |
-			           ((pixel >> 14) & 0x3);
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 1: /* 1/4/8 bit bmp -> 16 bit DIB */
-	    case 4:
-	    case 8:
-	        palEntry = palette->logpalette.palPalEntry;
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = ((palEntry[pixel].peBlue >> 3) & 0x1f) |
-			           ((palEntry[pixel].peGreen << 2) & 0xe0); 
-			*bbits++ = ((palEntry[pixel].peGreen >> 6) & 0x3) |
-			           ((palEntry[pixel].peRed >> 1) & 0x7c);
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    default: /* ? bit bmp -> 16 bit DIB */
-	        FIXME(bitmap, "15/16 bit DIB %d bit bitmap\n",
-				  bmp->bitmap.bmBitsPixel);
-		break;
-	    }
-	    break;
-
-
-	case 24: /* 24 bit DIB */
-	    switch(bmp->bitmap.bmBitsPixel) {
-
-	    case 24: /* 24/32 bit bmp -> 24 bit DIB */
-	    case 32:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = (pixel >>16) & 0xff;
-			*bbits++ = (pixel >> 8) & 0xff;
-			*bbits++ =  pixel       & 0xff;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 15: /* 15/16 bit bmp -> 24 bit DIB */
-	    case 16:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-		        *bbits++ = ((pixel >> 7) & 0xf8) |
-			           ((pixel >> 12) & 0x7);
-			*bbits++ = ((pixel >> 2) & 0xf8) |
-			           ((pixel >> 7) & 0x7);
-			*bbits++ = ((pixel << 3) & 0xf8) |
-			           ((pixel >> 2) & 0x7);
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 1: /* 1/4/8 bit bmp -> 24 bit DIB */
-	    case 4:
-	    case 8:
-	        palEntry = palette->logpalette.palPalEntry;
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = palEntry[pixel].peBlue;
-			*bbits++ = palEntry[pixel].peGreen;
-			*bbits++ = palEntry[pixel].peRed;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    default: /* ? bit bmp -> 24 bit DIB */
-	        FIXME(bitmap, "24 bit DIB %d bit bitmap\n",
-		      bmp->bitmap.bmBitsPixel);
-		break;
-	    }
-	    break;
-
-
-	case 32: /* 32 bit DIB */
-	    switch(bmp->bitmap.bmBitsPixel) {
-
-	    case 24: /* 24/32 bit bmp -> 32 bit DIB */
-	    case 32:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = (pixel >>16) & 0xff;
-			*bbits++ = (pixel >> 8) & 0xff;
-			*bbits++ =  pixel       & 0xff;
-			*bbits++ = 0;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 15: /* 15/16 bit bmp -> 32 bit DIB */
-	    case 16:
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-		        *bbits++ = ((pixel >> 7) & 0xf8) |
-			           ((pixel >> 12) & 0x7);
-			*bbits++ = ((pixel >> 2) & 0xf8) |
-			           ((pixel >> 7) & 0x7);
-			*bbits++ = ((pixel << 3) & 0xf8) |
-			           ((pixel >> 2) & 0x7);
-			*bbits++ = 0;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    case 1: /* 1/4/8 bit bmp -> 32 bit DIB */
-	    case 4:
-	    case 8:
-	        palEntry = palette->logpalette.palPalEntry;
-	        for( y = yend - 1; (int)y >= (int)startscan; y-- ) {
-		    for( x = 0; x < xend; x++ ) {
-		        unsigned long pixel=XGetPixel( bmpImage, x, y);
-			*bbits++ = palEntry[pixel].peBlue;
-			*bbits++ = palEntry[pixel].peGreen;
-			*bbits++ = palEntry[pixel].peRed;
-			*bbits++ = 0;
-		    }
-		    bbits = (linestart += dstwidth);
-		}
-		break;
-
-	    default: /* ? bit bmp -> 32 bit DIB */
-	        FIXME(bitmap, "32 bit DIB %d bit bitmap\n",
-		      bmp->bitmap.bmBitsPixel);
-		break;
-	    }
-	    break;
-
-
-	default: /* ? bit DIB */
-	    FIXME(bitmap,"Unsupported DIB depth %d\n",
-		  info->bmiHeader.biBitCount);
-	    break;
+	    return FALSE;
 	}
-
-	XDestroyImage( bmpImage );
-        LeaveCriticalSection( &X11DRV_CritSection );
-
-	if(info->bmiHeader.biSizeImage == 0) /* Fill in biSizeImage */
-	    info->bmiHeader.biSizeImage = info->bmiHeader.biHeight *
-	                    DIB_GetDIBWidthBytes( info->bmiHeader.biWidth,
-						  info->bmiHeader.biBitCount );
-
-	if(bbits - (BYTE *)bits > info->bmiHeader.biSizeImage)
-	    ERR(bitmap, "Buffer overrun. Please investigate.\n");
-
-	info->bmiHeader.biCompression = 0;
     }
     else if( info->bmiHeader.biSize >= sizeof(BITMAPINFOHEADER) ) 
     {
@@ -1002,8 +553,10 @@
     TRACE(bitmap, "biSizeImage = %ld, biWidth = %ld, biHeight = %ld\n",
 	  info->bmiHeader.biSizeImage, info->bmiHeader.biWidth,
 	  info->bmiHeader.biHeight);
+
+    GDI_HEAP_UNLOCK( hdc );
     GDI_HEAP_UNLOCK( hbitmap );
-    GDI_HEAP_UNLOCK( dc->w.hPalette );
+
     return lines;
 }
 
@@ -1089,198 +642,6 @@
     return handle;
 }
 
-
-/***********************************************************************
- *           DIB_DoProtectDIBSection
- */
-static void DIB_DoProtectDIBSection( BITMAPOBJ *bmp, DWORD new_prot )
-{
-    DIBSECTION *dib = &bmp->dib->dibSection;
-    INT effHeight = dib->dsBm.bmHeight >= 0? dib->dsBm.bmHeight
-                                             : -dib->dsBm.bmHeight;
-    INT totalSize = dib->dsBmih.biSizeImage? dib->dsBmih.biSizeImage
-                         : dib->dsBm.bmWidthBytes * effHeight;
-    DWORD old_prot;
-
-    VirtualProtect(dib->dsBm.bmBits, totalSize, new_prot, &old_prot);
-    TRACE(bitmap, "Changed protection from %ld to %ld\n", 
-                  old_prot, new_prot);
-}
-
-/***********************************************************************
- *           DIB_DoUpdateDIBSection
- */
-static void DIB_DoUpdateDIBSection( BITMAPOBJ *bmp, BOOL toDIB )
-{
-    DIBSECTIONOBJ *dib = bmp->dib;
-    DIB_SETIMAGEBITS_DESCR descr;
-
-    if (DIB_GetBitmapInfo( &dib->dibSection.dsBmih, &descr.infoWidth, &descr.lines,
-                           &descr.infoBpp, &descr.compression ) == -1)
-	return;
-
-    descr.dc        = NULL;
-    descr.image     = dib->image;
-    descr.colorMap  = dib->colorMap;
-    descr.nColorMap = dib->nColorMap;
-    descr.bits      = dib->dibSection.dsBm.bmBits;
-    descr.depth     = bmp->bitmap.bmBitsPixel;
-    
-    /* Hack for now */
-    descr.drawable  = ((X11DRV_PHYSBITMAP *)bmp->DDBitmap->physBitmap)->pixmap;
-    descr.gc        = BITMAP_GC(bmp);
-    descr.xSrc      = 0;
-    descr.ySrc      = 0;
-    descr.xDest     = 0;
-    descr.yDest     = 0;
-    descr.width     = bmp->bitmap.bmWidth;
-    descr.height    = bmp->bitmap.bmHeight;
-
-    if (toDIB)
-    {
-        TRACE(bitmap, "Copying from Pixmap to DIB bits\n");
-        EnterCriticalSection( &X11DRV_CritSection );
-        CALL_LARGE_STACK( X11DRV_DIB_GetImageBits, &descr );
-        LeaveCriticalSection( &X11DRV_CritSection );
-    }
-    else
-    {
-	TRACE(bitmap, "Copying from DIB bits to Pixmap\n"); 
-        EnterCriticalSection( &X11DRV_CritSection );
-        CALL_LARGE_STACK( X11DRV_DIB_SetImageBits, &descr );
-        LeaveCriticalSection( &X11DRV_CritSection );
-    }
-}
-
-/***********************************************************************
- *           DIB_FaultHandler
- */
-static BOOL DIB_FaultHandler( LPVOID res, LPCVOID addr )
-{
-    BOOL handled = FALSE;
-    BITMAPOBJ *bmp;
-
-    bmp = (BITMAPOBJ *)GDI_GetObjPtr( (HBITMAP)res, BITMAP_MAGIC );
-    if (!bmp) return FALSE;
-
-    if (bmp->dib)
-        switch (bmp->dib->status)
-        {
-        case DIB_GdiMod:
-            TRACE( bitmap, "called in status DIB_GdiMod\n" );
-            DIB_DoProtectDIBSection( bmp, PAGE_READWRITE );
-            DIB_DoUpdateDIBSection( bmp, TRUE );
-            DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
-            bmp->dib->status = DIB_InSync;
-            handled = TRUE;
-            break;
-
-        case DIB_InSync:
-            TRACE( bitmap, "called in status DIB_InSync\n" );
-            DIB_DoProtectDIBSection( bmp, PAGE_READWRITE );
-            bmp->dib->status = DIB_AppMod;
-            handled = TRUE;
-            break;
-
-        case DIB_AppMod:
-            FIXME( bitmap, "called in status DIB_AppMod: "
-                           "this can't happen!\n" );
-            break;
-
-        case DIB_NoHandler:
-            FIXME( bitmap, "called in status DIB_NoHandler: "
-                           "this can't happen!\n" );
-            break;
-        }
-
-    GDI_HEAP_UNLOCK( (HBITMAP)res );
-    return handled;
-}
-
-/***********************************************************************
- *           DIB_UpdateDIBSection
- */
-void DIB_UpdateDIBSection( DC *dc, BOOL toDIB )
-{
-    BITMAPOBJ *bmp;
-
-    /* Ensure this is a Compatible DC that has a DIB section selected */
-
-    if (!dc) return;
-    if (!(dc->w.flags & DC_MEMORY)) return;
-
-    bmp = (BITMAPOBJ *)GDI_GetObjPtr( dc->w.hBitmap, BITMAP_MAGIC );
-    if (!bmp) return;
-
-    if (!bmp->dib)
-    {
-	GDI_HEAP_UNLOCK(dc->w.hBitmap);
-	return;
-    }
-
-
-    if (!toDIB)
-    {
-        /* Prepare for access to the DIB by GDI functions */
-
-        switch (bmp->dib->status)
-        {
-        default:
-        case DIB_NoHandler:
-            DIB_DoUpdateDIBSection( bmp, FALSE );
-            break;
-
-        case DIB_GdiMod:
-            TRACE( bitmap, "fromDIB called in status DIB_GdiMod\n" );
-            /* nothing to do */
-            break;
-
-        case DIB_InSync:
-            TRACE( bitmap, "fromDIB called in status DIB_InSync\n" );
-            /* nothing to do */
-            break;
-
-        case DIB_AppMod:
-            TRACE( bitmap, "fromDIB called in status DIB_AppMod\n" );
-            DIB_DoUpdateDIBSection( bmp, FALSE );
-            DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
-            bmp->dib->status = DIB_InSync;
-            break;
-        }
-    }
-    else
-    {
-        /* Acknowledge write access to the DIB by GDI functions */
-
-        switch (bmp->dib->status)
-        {
-        default:
-        case DIB_NoHandler:
-            DIB_DoUpdateDIBSection( bmp, TRUE );
-            break;
-
-        case DIB_GdiMod:
-            TRACE( bitmap, "  toDIB called in status DIB_GdiMod\n" );
-            /* nothing to do */
-            break;
-
-        case DIB_InSync:
-            TRACE( bitmap, "  toDIB called in status DIB_InSync\n" );
-            DIB_DoProtectDIBSection( bmp, PAGE_NOACCESS );
-            bmp->dib->status = DIB_GdiMod;
-            break;
-
-        case DIB_AppMod:
-            FIXME( bitmap, "  toDIB called in status DIB_AppMod: "
-                           "this can't happen!\n" );
-            break;
-        }
-    }
-
-  
-    GDI_HEAP_UNLOCK(dc->w.hBitmap);
-}
-
 /***********************************************************************
  *           CreateDIBSection16    (GDI.489)
  */
@@ -1288,163 +649,35 @@
 				     SEGPTR *bits, HANDLE section,
 				     DWORD offset)
 {
-    HBITMAP res = CreateDIBSection(hdc, bmi, usage, NULL, section,
-				       offset);
+    HBITMAP16 hbitmap;
+    DC *dc = (DC *) GDI_GetObjPtr(hdc, DC_MAGIC);
+    if(!dc) dc = (DC *) GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
+    if(!dc) return (HBITMAP16) NULL;
 
-    if ( res )
-    {
-	BITMAPOBJ *bmp = (BITMAPOBJ *) GDI_GetObjPtr(res, BITMAP_MAGIC);
-	if ( bmp && bmp->dib )
-	{
-	    DIBSECTION *dib = &bmp->dib->dibSection;
-	    INT height = dib->dsBm.bmHeight >= 0 ?
-		dib->dsBm.bmHeight : -dib->dsBm.bmHeight;
-	    INT size = dib->dsBmih.biSizeImage ?
-		dib->dsBmih.biSizeImage : dib->dsBm.bmWidthBytes * height;
-	    if ( dib->dsBm.bmBits )
-	    {
-		bmp->dib->selector = 
-		    SELECTOR_AllocBlock( dib->dsBm.bmBits, size, 
-					 SEGMENT_DATA, FALSE, FALSE );
-	    }
-	    printf("ptr = %p, size =%d, selector = %04x, segptr = %ld\n",
-		   dib->dsBm.bmBits, size, bmp->dib->selector,
-		   PTR_SEG_OFF_TO_SEGPTR(bmp->dib->selector, 0));
-}
-	GDI_HEAP_UNLOCK( res );
+    hbitmap = dc->funcs->pCreateDIBSection16(dc, bmi, usage, bits, section, offset);
 
-	if ( bits ) 
-	    *bits = PTR_SEG_OFF_TO_SEGPTR( bmp->dib->selector, 0 );
-    }
+    GDI_HEAP_UNLOCK(hdc);
 
-    return res;
+    return hbitmap;
 }
 
 /***********************************************************************
  *           CreateDIBSection32    (GDI32.36)
  */
-HBITMAP WINAPI CreateDIBSection (HDC hdc, BITMAPINFO *bmi, UINT usage,
-				     LPVOID *bits,HANDLE section,
-				     DWORD offset)
+HBITMAP WINAPI CreateDIBSection(HDC hdc, BITMAPINFO *bmi, UINT usage,
+				LPVOID *bits, HANDLE section,
+				DWORD offset)
 {
-    HBITMAP res = 0;
-    BITMAPOBJ *bmp = NULL;
-    DIBSECTIONOBJ *dib = NULL;
-    int *colorMap = NULL;
-    int nColorMap;
+    HBITMAP hbitmap;
+    DC *dc = (DC *) GDI_GetObjPtr(hdc, DC_MAGIC);
+    if(!dc) dc = (DC *) GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
+    if(!dc) return (HBITMAP) NULL;
 
-    /* Fill BITMAP32 structure with DIB data */
-    BITMAPINFOHEADER *bi = &bmi->bmiHeader;
-    INT effHeight, totalSize;
-    BITMAP bm;
+    hbitmap = dc->funcs->pCreateDIBSection(dc, bmi, usage, bits, section, offset);
 
-    TRACE(bitmap, "format (%ld,%ld), planes %d, bpp %d, size %ld, colors %ld (%s)\n",
-	  bi->biWidth, bi->biHeight, bi->biPlanes, bi->biBitCount,
-	  bi->biSizeImage, bi->biClrUsed, usage == DIB_PAL_COLORS? "PAL" : "RGB");
+    GDI_HEAP_UNLOCK(hdc);
 
-    bm.bmType = 0;
-    bm.bmWidth = bi->biWidth;
-    bm.bmHeight = bi->biHeight;
-    bm.bmWidthBytes = DIB_GetDIBWidthBytes(bm.bmWidth, bi->biBitCount);
-    bm.bmPlanes = bi->biPlanes;
-    bm.bmBitsPixel = bi->biBitCount;
-    bm.bmBits = NULL;
-
-    /* Get storage location for DIB bits */
-    effHeight = bm.bmHeight >= 0 ? bm.bmHeight : -bm.bmHeight;
-    totalSize = bi->biSizeImage? bi->biSizeImage : bm.bmWidthBytes * effHeight;
-
-    if (section)
-        bm.bmBits = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 
-                                  0L, offset, totalSize);
-    else
-	bm.bmBits = VirtualAlloc(NULL, totalSize, 
-                                 MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
-
-    /* Create Color Map */
-    if (bm.bmBits && bm.bmBitsPixel <= 8)
-    {
-        DC *dc = hdc? (DC *)GDI_GetObjPtr(hdc, DC_MAGIC) : NULL;
-        if (hdc && !dc) dc = (DC *)GDI_GetObjPtr(hdc, METAFILE_DC_MAGIC);
-
-        if (!hdc || dc)
-            colorMap = X11DRV_DIB_BuildColorMap( dc, usage, bm.bmBitsPixel,
-						 bmi, &nColorMap );
-        GDI_HEAP_UNLOCK(hdc);
-    }
-
-    /* Allocate Memory for DIB and fill structure */
-    if (bm.bmBits)
-	dib = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DIBSECTIONOBJ));
-    if (dib)
-    {
-	dib->dibSection.dsBm = bm;
-	dib->dibSection.dsBmih = *bi;
-	/* FIXME: dib->dibSection.dsBitfields ??? */
-	dib->dibSection.dshSection = section;
-	dib->dibSection.dsOffset = offset;
-
-        dib->status    = DIB_NoHandler;
-	dib->selector  = 0;
-        
-	dib->nColorMap = nColorMap;
-        dib->colorMap  = colorMap;
-    }
-
-    /* Create Device Dependent Bitmap and add DIB pointer */
-    if (dib) 
-    {
-       res = CreateDIBitmap(hdc, bi, 0, NULL, bmi, usage);
-       if (res)
-       {
-           bmp = (BITMAPOBJ *) GDI_GetObjPtr(res, BITMAP_MAGIC);
-           if (bmp)
-           {
-               bmp->dib = dib;
-               /* HACK for now */
-               if(!bmp->DDBitmap)
-                   X11DRV_CreateBitmap(res); 
-           }
-       }
-    }
-
-    /* Create XImage */
-    if (dib && bmp)
-        XCREATEIMAGE( dib->image, bm.bmWidth, effHeight, bmp->bitmap.bmBitsPixel );
-
-    /* Clean up in case of errors */
-    if (!res || !bmp || !dib || !bm.bmBits || (bm.bmBitsPixel <= 8 && !colorMap))
-    {
-        TRACE(bitmap, "got an error res=%08x, bmp=%p, dib=%p, bm.bmBits=%p\n",
-              res, bmp, dib, bm.bmBits);
-	if (bm.bmBits)
-        {
-            if (section)
-                UnmapViewOfFile(bm.bmBits), bm.bmBits = NULL;
-            else
-                VirtualFree(bm.bmBits, MEM_RELEASE, 0L), bm.bmBits = NULL;
-        }
-
-        if (dib && dib->image) { XDestroyImage(dib->image); dib->image = NULL; }
-	if (colorMap) { HeapFree(GetProcessHeap(), 0, colorMap); colorMap = NULL; }
-	if (dib) { HeapFree(GetProcessHeap(), 0, dib); dib = NULL; }
-	if (res) { DeleteObject(res); res = 0; }
-    }
-
-    /* Install fault handler, if possible */
-    if (bm.bmBits)
-    {
-        if (VIRTUAL_SetFaultHandler(bm.bmBits, DIB_FaultHandler, (LPVOID)res))
-        {
-            DIB_DoProtectDIBSection( bmp, PAGE_READONLY );
-            if (dib) dib->status = DIB_InSync;
-        }
-    }
-
-    /* Return BITMAP handle and storage location */
-    if (res) GDI_HEAP_UNLOCK(res);
-    if (bm.bmBits && bits) *bits = bm.bmBits;
-    return res;
+    return hbitmap;
 }
 
 /***********************************************************************
@@ -1454,27 +687,17 @@
 {
     if (bmp && bmp->dib)
     {
-        DIBSECTIONOBJ *dib = bmp->dib;
+        DIBSECTION *dib = bmp->dib;
 
-        if (dib->dibSection.dsBm.bmBits)
+        if (dib->dsBm.bmBits)
         {
-            if (dib->dibSection.dshSection)
-                UnmapViewOfFile(dib->dibSection.dsBm.bmBits);
+            if (dib->dshSection)
+                UnmapViewOfFile(dib->dsBm.bmBits);
             else
-                VirtualFree(dib->dibSection.dsBm.bmBits, MEM_RELEASE, 0L);
+                VirtualFree(dib->dsBm.bmBits, MEM_RELEASE, 0L);
         }
 
-        if (dib->image) 
-            XDestroyImage( dib->image );
-
-        if (dib->colorMap)
-            HeapFree(GetProcessHeap(), 0, dib->colorMap);
-
-        if (dib->selector)
-        {
-            WORD count = (GET_SEL_LIMIT( dib->selector ) >> 16) + 1;
-            SELECTOR_FreeBlock( dib->selector, count );
-        }
+	BITMAP_Driver->pDeleteDIBSection(bmp);
 
         HeapFree(GetProcessHeap(), 0, dib);
         bmp->dib = NULL;
diff --git a/objects/gdiobj.c b/objects/gdiobj.c
index 0996f85..24388bc 100644
--- a/objects/gdiobj.c
+++ b/objects/gdiobj.c
@@ -4,15 +4,14 @@
  * Copyright 1993 Alexandre Julliard
  */
 
-#include "config.h"
-
 #ifndef X_DISPLAY_MISSING
 #include "x11drv.h"
 #else /* !defined(X_DISPLAY_MISSING) */
 #include "ttydrv.h"
-#endif /* !defined(X_DISPLAY_MISSING) */
+#endif /* !defined(X_DISPLAY_MISSING */
 
 #include <stdlib.h>
+
 #include "bitmap.h"
 #include "brush.h"
 #include "dc.h"
@@ -25,6 +24,10 @@
 #include "debug.h"
 #include "gdi.h"
 
+/**********************************************************************/
+
+GDI_DRIVER *GDI_Driver = NULL;
+
 /***********************************************************************
  *          GDI stock objects 
  */
@@ -251,16 +254,16 @@
     /* Initialize drivers */
 
 #ifndef X_DISPLAY_MISSING
-    if( ! X11DRV_Init() )
-        return FALSE;
+    GDI_Driver = &X11DRV_GDI_Driver;
 #else /* !defined(X_DISPLAY_MISSING) */
-    if( ! TTYDRV_GDI_Initialize() )
-        return FALSE;    
-#endif /* !defined(X_DISPLAY_MISSING) */
+    GDI_Driver = &TTYDRV_GDI_Driver;
+#endif /* !defined(X_DISPLAY_MISSING */
 
-	/* Create default palette */
+    GDI_Driver->pInitialize();
 
-      /* DR well *this* palette can't be moveable (?) */
+    /* Create default palette */
+
+    /* DR well *this* palette can't be moveable (?) */
     {
     HPALETTE16 hpalette = PALETTE_Init();
     if( !hpalette )
diff --git a/objects/palette.c b/objects/palette.c
index 27afd1d..245a60a 100644
--- a/objects/palette.c
+++ b/objects/palette.c
@@ -10,6 +10,7 @@
 
 #include <stdlib.h>
 #include <string.h>
+
 #include "gdi.h"
 #include "color.h"
 #include "palette.h"
@@ -17,6 +18,8 @@
 #include "debug.h"
 #include "wine/winuser16.h"
 
+PALETTE_DRIVER *PALETTE_Driver = NULL;
+
 FARPROC pfnSelectPalette = NULL;
 FARPROC pfnRealizePalette = NULL;
 
@@ -134,7 +137,7 @@
     HDC16 hdc) /* [in] Handle to device context */
 {
     return CreateHalftonePalette(hdc);
-	}
+}
 
 	
 /***********************************************************************
@@ -381,8 +384,9 @@
 	    UINT u;
 	    for( u = 0; u < NumEntries; u++ )
 		palPtr->logpalette.palPalEntry[u + StartIndex] = PaletteColors[u];
-	    COLOR_SetMapping(palPtr, StartIndex, NumEntries,
-                             hPal != hPrimaryPalette );
+	    PALETTE_Driver->
+	      pSetMapping(palPtr, StartIndex, NumEntries,
+			  hPal != hPrimaryPalette );
             GDI_HEAP_UNLOCK( hPal );
 	    return TRUE;
 	}
@@ -469,7 +473,7 @@
     TRACE(palette, "hdc=%04x,start=%i,count=%i\n", hdc,start,count);
 
     if (!(dc = (DC *) GDI_GetObjPtr( hdc, DC_MAGIC ))) return 0;
-    if (!entries) return COLOR_GetSystemPaletteSize();
+    if (!entries) return dc->w.devCaps->sizePalette;
     if (start >= dc->w.devCaps->sizePalette)
       {
 	GDI_HEAP_UNLOCK( hdc );
@@ -516,9 +520,9 @@
     UINT index  = 0;
 
     if( palObj )
-        index = COLOR_PaletteLookupPixel( palObj->logpalette.palPalEntry, 
-				          palObj->logpalette.palNumEntries,
-                                          NULL, color, FALSE );
+      index = COLOR_PaletteLookupPixel(palObj->logpalette.palPalEntry, 
+				       palObj->logpalette.palNumEntries,
+				       NULL, color, FALSE );
 
     TRACE(palette,"(%04x,%06lx): returning %d\n", hpalette, color, index );
     GDI_HEAP_UNLOCK( hpalette );
@@ -660,9 +664,10 @@
 		return 0;
 	}
         
-        realized = COLOR_SetMapping(palPtr,0,palPtr->logpalette.palNumEntries,
-                                    (dc->w.hPalette != hPrimaryPalette) ||
-                                    (dc->w.hPalette == STOCK_DEFAULT_PALETTE));
+        realized = PALETTE_Driver->
+	  pSetMapping(palPtr,0,palPtr->logpalette.palNumEntries,
+		      (dc->w.hPalette != hPrimaryPalette) ||
+		      (dc->w.hPalette == STOCK_DEFAULT_PALETTE));
 	GDI_HEAP_UNLOCK( dc->w.hPalette );
 	hLastRealizedPalette = dc->w.hPalette;
     }
@@ -682,7 +687,6 @@
 {
     DC          *dc;
     PALETTEOBJ*  palPtr;
-    int          i, index, realized = 0;
 
     TRACE(palette,"%04x\n", hdc );
 
@@ -707,15 +711,7 @@
 
     /* lookup is needed to account for SetSystemPaletteUse() stuff */
 
-    for( i = 0; i < 20; i++ )
-       {
-         index = COLOR_LookupSystemPixel(*(COLORREF*)(palPtr->logpalette.palPalEntry + i));
-
-         /* mapping is allocated in COLOR_InitPalette() */
-
-         if( index != palPtr->mapping[i] ) { palPtr->mapping[i]=index; realized++; }
-       }
-    return realized;
+    return PALETTE_Driver->pUpdateMapping(palPtr);
 }
 
 /***********************************************************************
@@ -798,12 +794,17 @@
 UINT WINAPI RealizePalette(
     HDC hDC) /* [in] Handle of device context */
 {
-    UINT realized = GDIRealizePalette16( hDC );
+    DC *dc;
+    UINT realized;
+
+    if (!(dc = (DC *) GDI_GetObjPtr( hDC, DC_MAGIC ))) return 0;
+    
+    realized = GDIRealizePalette16( hDC );
 
     /* do not send anything if no colors were changed */
 
-    if( IsDCCurrentPalette16( hDC ) && realized && 
-        !(COLOR_GetSystemPaletteFlags() & COLOR_VIRTUAL) )
+    if( IsDCCurrentPalette16( hDC ) && realized &&
+	dc->w.devCaps->sizePalette )
     {
 	/* Send palette change notification */
 
@@ -811,6 +812,8 @@
  	if( (hWnd = WindowFromDC( hDC )) )
             SendMessage16( HWND_BROADCAST, WM_PALETTECHANGED, hWnd, 0L);
     }
+
+    GDI_HEAP_UNLOCK( hDC );
     return realized;
 }
 
@@ -820,13 +823,21 @@
  */
 INT16 WINAPI UpdateColors16( HDC16 hDC )
 {
-    HWND hWnd = WindowFromDC( hDC );
+    DC *dc;
+    HWND hWnd;
+
+    if (!(dc = (DC *) GDI_GetObjPtr( hDC, DC_MAGIC ))) return 0;
+
+    hWnd = WindowFromDC( hDC );
 
     /* Docs say that we have to remap current drawable pixel by pixel
      * but it would take forever given the speed of XGet/PutPixel.
      */
-    if (hWnd && !(COLOR_GetSystemPaletteFlags() & COLOR_VIRTUAL) ) 
+    if (hWnd && dc->w.devCaps->sizePalette ) 
 	InvalidateRect( hWnd, NULL, FALSE );
+
+    GDI_HEAP_UNLOCK( hDC );
+
     return 0x666;
 }
 
diff --git a/objects/region.c b/objects/region.c
index 6a92c21..0ee4c8e 100644
--- a/objects/region.c
+++ b/objects/region.c
@@ -821,7 +821,6 @@
  *           REGION_LPTODP
  *
  * Convert region to device co-ords for the supplied dc. 
- * Used by X11DRV_PaintRgn.
  */
 BOOL REGION_LPTODP( HDC hdc, HRGN hDest, HRGN hSrc )
 {
diff --git a/windows/clipboard.c b/windows/clipboard.c
index c7af89c..75a1a1e 100644
--- a/windows/clipboard.c
+++ b/windows/clipboard.c
@@ -21,18 +21,14 @@
 #include "xmalloc.h"
 #include "debug.h"
 
-#ifndef X_DISPLAY_MISSING
-extern CLIPBOARD_DRIVER X11DRV_CLIPBOARD_Driver;
-#else /* X_DISPLAY_MISSING */
-extern CLIPBOARD_DRIVER TTYDRV_CLIPBOARD_Driver;
-#endif /* X_DISPLAY_MISSING */
-
 #define  CF_REGFORMATBASE 	0xC000
 
 /**************************************************************************
  *			internal variables
  */
 
+CLIPBOARD_DRIVER *CLIPBOARD_Driver = NULL;
+
 static HQUEUE16 hqClipLock   = 0;
 static BOOL bCBHasChanged  = FALSE;
 
@@ -72,19 +68,6 @@
     return lpFormat;
 }
 
-
-/**************************************************************************
- *		CLIPBOARD_GetDriver
- */
-CLIPBOARD_DRIVER *CLIPBOARD_GetDriver()
-{
-#ifndef X_DISPLAY_MISSING
-  return &X11DRV_CLIPBOARD_Driver;
-#else /* X_DISPLAY_MISSING */
-  return &TTYDRV_CLIPBOARD_Driver;
-#endif /* X_DISPLAY_MISSING */
-};
-
 /**************************************************************************
  *                      CLIPBOARD_ResetLock
  */
@@ -267,7 +250,7 @@
 
     hWndClipOwner = hWndClipWindow;
 
-    CLIPBOARD_GetDriver()->pEmptyClipboard();
+    CLIPBOARD_Driver->pEmptyClipboard();
 
     return TRUE;
 }
@@ -310,7 +293,7 @@
     if( (hqClipLock != GetFastQueue16()) || !lpFormat ||
 	(!hData && (!hWndClipOwner || (hWndClipOwner != hWndClipWindow))) ) return 0; 
 
-    CLIPBOARD_GetDriver()->pSetClipboardData(wFormat);
+    CLIPBOARD_Driver->pSetClipboardData(wFormat);
 
     if ( lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32 ) 
     {
@@ -358,7 +341,7 @@
     if( (hqClipLock != GetFastQueue16()) || !lpFormat ||
 	(!hData && (!hWndClipOwner || (hWndClipOwner != hWndClipWindow))) ) return 0; 
 
-    CLIPBOARD_GetDriver()->pSetClipboardData(wFormat);
+    CLIPBOARD_Driver->pSetClipboardData(wFormat);
 
     if ( lpFormat->wDataPresent || lpFormat->hData16 || lpFormat->hData32 ) 
     {
@@ -626,7 +609,7 @@
     TRACE(clipboard,"(void)\n");
 
     /* FIXME: Returns BOOL32 */
-    CLIPBOARD_GetDriver()->pRequestSelection();
+    CLIPBOARD_Driver->pRequestSelection();
 
     FormatCount += abs(lpFormat[CF_TEXT-1].wDataPresent -
 		       lpFormat[CF_OEMTEXT-1].wDataPresent); 
@@ -668,7 +651,7 @@
     if( hqClipLock != GetFastQueue16() ) return 0;
 
     if( (!wFormat || wFormat == CF_TEXT || wFormat == CF_OEMTEXT) ) 
-        CLIPBOARD_GetDriver()->pRequestSelection();
+        CLIPBOARD_Driver->pRequestSelection();
 
     if (wFormat == 0)
     {
@@ -895,7 +878,7 @@
     TRACE(clipboard,"(%04X) !\n", wFormat);
 
     if( (wFormat == CF_TEXT || wFormat == CF_OEMTEXT) )
-        CLIPBOARD_GetDriver()->pRequestSelection();
+        CLIPBOARD_Driver->pRequestSelection();
 
     return CLIPBOARD_IsPresent(wFormat);
 }
diff --git a/windows/dce.c b/windows/dce.c
index ad8433c..2f52572 100644
--- a/windows/dce.c
+++ b/windows/dce.c
@@ -17,8 +17,7 @@
  * DCX_WINDOWPAINT - BeginPaint() is in effect
  */
 
-#include "x11drv.h"
-
+#include "desktop.h"
 #include "options.h"
 #include "dce.h"
 #include "class.h"
@@ -798,11 +797,9 @@
 		hrgnVisible = CreateRectRgn( 0, 0, 0, 0 );
             WIN_ReleaseWndPtr(parentPtr);
         }
-        else 
-	    if ((hwnd == GetDesktopWindow()) &&
-                (X11DRV_WND_GetXRootWindow(wndPtr) == DefaultRootWindow(display)))
-                 hrgnVisible = CreateRectRgn( 0, 0, SYSMETRICS_CXSCREEN,
-						      SYSMETRICS_CYSCREEN );
+        else
+	    if ((hwnd == GetDesktopWindow()) && !DESKTOP_IsSingleWindow())
+                 hrgnVisible = CreateRectRgn( 0, 0, SYSMETRICS_CXSCREEN, SYSMETRICS_CYSCREEN );
 	    else 
             {
                 hrgnVisible = DCE_GetVisRgn( hwnd, flags, 0, 0 );
diff --git a/windows/defwnd.c b/windows/defwnd.c
index 3bd9e15..94f7d0c 100644
--- a/windows/defwnd.c
+++ b/windows/defwnd.c
@@ -6,6 +6,7 @@
  */
 
 #include <string.h>
+
 #include "win.h"
 #include "user.h"
 #include "heap.h"
diff --git a/windows/display.c b/windows/display.c
index 7909a69..9f1b7cf 100644
--- a/windows/display.c
+++ b/windows/display.c
@@ -5,29 +5,11 @@
  *
  */
 
-#include "config.h"
-
-#include "display.h"
 #include "debug.h"
+#include "display.h"
+#include "mouse.h"
 #include "windef.h"
-
-#ifndef X_DISPLAY_MISSING
-extern MOUSE_DRIVER X11DRV_MOUSE_Driver;
-#else /* X_DISPLAY_MISSING */
-extern MOUSE_DRIVER TTYDRV_MOUSE_Driver;
-#endif /* X_DISPLAY_MISSING */
-
-/***********************************************************************
- *           MOUSE_GetDriver()
- */
-MOUSE_DRIVER *MOUSE_GetDriver()
-{
-#ifndef X_DISPLAY_MISSING
-  return &X11DRV_MOUSE_Driver;
-#else /* X_DISPLAY_MISSING */
-  return &TTYDRV_MOUSE_Driver;
-#endif /* X_DISPLAY_MISSING */
-}
+#include "wine/winuser16.h"
 
 /***********************************************************************
  *           DISPLAY_Inquire			(DISPLAY.101)
@@ -45,7 +27,7 @@
  */
 VOID WINAPI DISPLAY_SetCursor( CURSORICONINFO *lpCursor )
 {
-   MOUSE_GetDriver()->pSetCursor(lpCursor);
+   MOUSE_Driver->pSetCursor(lpCursor);
 }
 
 /***********************************************************************
@@ -53,7 +35,7 @@
  */
 VOID WINAPI DISPLAY_MoveCursor( WORD wAbsX, WORD wAbsY )
 {
-   MOUSE_GetDriver()->pMoveCursor(wAbsX, wAbsY);
+   MOUSE_Driver->pMoveCursor(wAbsX, wAbsY);
 }
 
 /***********************************************************************
diff --git a/windows/event.c b/windows/event.c
index 636cb11..5deeb86 100644
--- a/windows/event.c
+++ b/windows/event.c
@@ -5,27 +5,11 @@
  * 
  */
 
-#include "config.h"
-
 #include "message.h"
 
-#ifndef X_DISPLAY_MISSING
-extern EVENT_DRIVER X11DRV_EVENT_Driver;
-#else /* X_DISPLAY_MISSING */
-extern EVENT_DRIVER TTYDRV_EVENT_Driver;
-#endif /* X_DISPLAY_MISSING */
+/**********************************************************************/
 
-/***********************************************************************
- *		EVENT_GetDriver
- */
-EVENT_DRIVER *EVENT_GetDriver(void)
-{
-#ifndef X_DISPLAY_MISSING
-  return &X11DRV_EVENT_Driver;
-#else /* X_DISPLAY_MISSING */
-  return &TTYDRV_EVENT_Driver;
-#endif /* X_DISPLAY_MISSING */
-}
+EVENT_DRIVER *EVENT_Driver = NULL;
 
 /***********************************************************************
  *		EVENT_Init
@@ -34,7 +18,7 @@
  */
 BOOL EVENT_Init(void)
 {
-  return EVENT_GetDriver()->pInit();
+  return EVENT_Driver->pInit();
 }
 
 /***********************************************************************
@@ -42,7 +26,7 @@
  */
 void EVENT_AddIO(int fd, unsigned io_type)
 {
-  EVENT_GetDriver()->pAddIO(fd, io_type);
+  EVENT_Driver->pAddIO(fd, io_type);
 }
 
 /***********************************************************************
@@ -50,7 +34,7 @@
  */
 void EVENT_DeleteIO(int fd, unsigned io_type)
 {
-  EVENT_GetDriver()->pDeleteIO(fd, io_type);
+  EVENT_Driver->pDeleteIO(fd, io_type);
 }
 
 /***********************************************************************
@@ -62,7 +46,7 @@
  */
 BOOL EVENT_WaitNetEvent(BOOL sleep, BOOL peek)
 {
-  return EVENT_GetDriver()->pWaitNetEvent(sleep, peek);
+  return EVENT_Driver->pWaitNetEvent(sleep, peek);
 }
 
 /***********************************************************************
@@ -72,7 +56,7 @@
  */
 void EVENT_Synchronize(void)
 {
-  EVENT_GetDriver()->pSynchronize();
+  EVENT_Driver->pSynchronize();
 }
 
 /**********************************************************************
@@ -80,7 +64,7 @@
  */
 BOOL EVENT_CheckFocus(void)
 {
-  return EVENT_GetDriver()->pCheckFocus();
+  return EVENT_Driver->pCheckFocus();
 }
 
 /***********************************************************************
@@ -88,7 +72,7 @@
  */
 BOOL EVENT_QueryPointer(DWORD *posX, DWORD *posY, DWORD *state)
 {
-  return EVENT_GetDriver()->pQueryPointer(posX, posY, state);
+  return EVENT_Driver->pQueryPointer(posX, posY, state);
 }
 
 
@@ -99,15 +83,15 @@
  */
 void EVENT_DummyMotionNotify(void)
 {
-  EVENT_GetDriver()->pDummyMotionNotify();
+  EVENT_Driver->pDummyMotionNotify();
 }
 
 /**********************************************************************
- *		X11DRV_EVENT_Pending
+ *		EVENT_Pending
  */
 BOOL EVENT_Pending()
 {
-  return EVENT_GetDriver()->pPending();
+  return EVENT_Driver->pPending();
 }
 
 /***********************************************************************
@@ -117,7 +101,7 @@
  */
 BOOL16 WINAPI IsUserIdle16(void)
 {
-  return EVENT_GetDriver()->pIsUserIdle();
+  return EVENT_Driver->pIsUserIdle();
 }
 
 /***********************************************************************
@@ -129,5 +113,5 @@
  */
 void EVENT_WakeUp(void)
 {
-  EVENT_GetDriver()->pWakeUp();
+  EVENT_Driver->pWakeUp();
 }
diff --git a/windows/keyboard.c b/windows/keyboard.c
index 2ddf793..fa39c62 100644
--- a/windows/keyboard.c
+++ b/windows/keyboard.c
@@ -9,11 +9,10 @@
  *
  */
 
-#include "config.h"
-
 #include <stdlib.h>
 #include <string.h>
 #include <ctype.h>
+
 #include "winuser.h"
 #include "wine/keyboard16.h"
 #include "win.h"
@@ -25,27 +24,13 @@
 #include "struct32.h"
 #include "winerror.h"
 
+/**********************************************************************/
+
+KEYBOARD_DRIVER *KEYBOARD_Driver = NULL;
+
 static LPKEYBD_EVENT_PROC DefKeybEventProc = NULL;
 LPBYTE pKeyStateTable = NULL;
 
-#ifndef X_DISPLAY_MISSING
-extern KEYBOARD_DRIVER X11DRV_KEYBOARD_Driver;
-#else /* X_DISPLAY_MISSING */
-extern KEYBOARD_DRIVER TTYDRV_KEYBOARD_Driver;
-#endif /* X_DISPLAY_MISSING */
-
-/***********************************************************************
- *           KEYBOARD_GetDriver
- */
-KEYBOARD_DRIVER *KEYBOARD_GetDriver()
-{
-#ifndef X_DISPLAY_MISSING
-  return &X11DRV_KEYBOARD_Driver;
-#else /* X_DISPLAY_MISSING */
-  return &TTYDRV_KEYBOARD_Driver;
-#endif /* X_DISPLAY_MISSING */
-}
-
 /***********************************************************************
  *           KEYBOARD_Inquire			(KEYBOARD.1)
  */
@@ -74,7 +59,7 @@
   /* all states to false */
   memset( lpKeyState, 0, sizeof(lpKeyState) );
   
-  if (!initDone) KEYBOARD_GetDriver()->pInit();
+  if (!initDone) KEYBOARD_Driver->pInit();
   initDone = TRUE;
 }
 
@@ -145,7 +130,7 @@
 
 WORD WINAPI VkKeyScan16(CHAR cChar)
 {
-  return KEYBOARD_GetDriver()->pVkKeyScan(cChar);
+  return KEYBOARD_Driver->pVkKeyScan(cChar);
 }
 
 /******************************************************************************
@@ -178,7 +163,7 @@
  */
 UINT16 WINAPI MapVirtualKey16(UINT16 wCode, UINT16 wMapType)
 {
-  return KEYBOARD_GetDriver()->pMapVirtualKey(wCode,wMapType);
+  return KEYBOARD_Driver->pMapVirtualKey(wCode,wMapType);
 }
 
 /****************************************************************************
@@ -195,7 +180,7 @@
  */
 INT16 WINAPI GetKeyNameText16(LONG lParam, LPSTR lpBuffer, INT16 nSize)
 {
-  return KEYBOARD_GetDriver()->pGetKeyNameText(lParam, lpBuffer, nSize);
+  return KEYBOARD_Driver->pGetKeyNameText(lParam, lpBuffer, nSize);
 }
 
 /****************************************************************************
@@ -219,8 +204,32 @@
 INT16 WINAPI ToAscii16(UINT16 virtKey,UINT16 scanCode, LPBYTE lpKeyState, 
                        LPVOID lpChar, UINT16 flags) 
 {
-    return KEYBOARD_GetDriver()->pToAscii(
+    return KEYBOARD_Driver->pToAscii(
         virtKey, scanCode, lpKeyState, lpChar, flags
     );
 }
 
+/***********************************************************************
+ *		KEYBOARD_GetBeepActive
+ */
+BOOL KEYBOARD_GetBeepActive()
+{
+  return KEYBOARD_Driver->pGetBeepActive();
+}
+
+/***********************************************************************
+ *		KEYBOARD_SetBeepActive
+ */
+void KEYBOARD_SetBeepActive(BOOL bActivate)
+{
+  KEYBOARD_Driver->pSetBeepActive(bActivate);
+}
+
+/***********************************************************************
+ *		KEYBOARD_Beep
+ */
+void KEYBOARD_Beep(void)
+{
+  KEYBOARD_Driver->pBeep();
+}
+
diff --git a/windows/mouse.c b/windows/mouse.c
index 64f4998..cfd59f1 100644
--- a/windows/mouse.c
+++ b/windows/mouse.c
@@ -5,17 +5,14 @@
  * 
  */
 
-#include <assert.h>
-#include "winuser.h"
-#include "gdi.h"
-#include "mouse.h"
 #include "debug.h"
-#include "debugtools.h"
+#include "mouse.h"
 #include "monitor.h"
+#include "winuser.h"
 
 /**********************************************************************/
 
-extern BOOL X11DRV_MOUSE_DisableWarpPointer;
+MOUSE_DRIVER *MOUSE_Driver = NULL;
 
 static LPMOUSE_EVENT_PROC DefMouseEventProc = NULL;
 
@@ -62,6 +59,7 @@
     int width  = MONITOR_GetWidth (&MONITOR_PrimaryMonitor);
     int height = MONITOR_GetHeight(&MONITOR_PrimaryMonitor);
     WINE_MOUSEEVENT wme;
+    BOOL bOldWarpPointer;
 
     if ( !DefMouseEventProc ) return;
 
@@ -76,8 +74,7 @@
     wme.time     = time;
     wme.hWnd     = hWnd;
 
-    X11DRV_MOUSE_DisableWarpPointer = TRUE;
+    bOldWarpPointer = MOUSE_Driver->pEnableWarpPointer(FALSE);
     DefMouseEventProc( mouseStatus, posX, posY, 0, (DWORD)&wme );
-    X11DRV_MOUSE_DisableWarpPointer = FALSE;
+    MOUSE_Driver->pEnableWarpPointer(bOldWarpPointer);
 }
-
diff --git a/windows/multimon.c b/windows/multimon.c
index 12ba428..5dc3987 100644
--- a/windows/multimon.c
+++ b/windows/multimon.c
@@ -4,9 +4,13 @@
  * Copyright 1998 Turchanov Sergey
  */
 
+#include "monitor.h"
 #include "winbase.h"
 #include "winuser.h"
-#include "monitor.h"
+
+/**********************************************************************/
+
+MONITOR_DRIVER *MONITOR_Driver;
 
 /**********************************************************************/
 
@@ -15,11 +19,26 @@
 MONITOR MONITOR_PrimaryMonitor;
 
 /***********************************************************************
+ *              MONITOR_GetMonitor
+ */
+MONITOR *MONITOR_GetMonitor(HMONITOR hMonitor)
+{
+  if(hMonitor == xPRIMARY_MONITOR)
+    {
+      return &MONITOR_PrimaryMonitor;
+    }
+  else
+    {
+      return NULL;
+    }
+}
+
+/***********************************************************************
  *              MONITOR_Initialize
  */
 void MONITOR_Initialize(MONITOR *pMonitor)
 {
-  pMonitor->pDriver->pInitialize(pMonitor);
+  MONITOR_Driver->pInitialize(pMonitor);
 }
 
 /***********************************************************************
@@ -27,7 +46,15 @@
  */
 void MONITOR_Finalize(MONITOR *pMonitor)
 {
-  pMonitor->pDriver->pFinalize(pMonitor);
+  MONITOR_Driver->pFinalize(pMonitor);
+}
+
+/***********************************************************************
+ *              MONITOR_IsSingleWindow
+ */
+BOOL MONITOR_IsSingleWindow(MONITOR *pMonitor)
+{
+  return MONITOR_Driver->pIsSingleWindow(pMonitor);
 }
 
 /***********************************************************************
@@ -35,7 +62,7 @@
  */
 int MONITOR_GetWidth(MONITOR *pMonitor)
 {
-  return pMonitor->pDriver->pGetWidth(pMonitor);
+  return MONITOR_Driver->pGetWidth(pMonitor);
 }
 
 /***********************************************************************
@@ -43,7 +70,7 @@
  */
 int MONITOR_GetHeight(MONITOR *pMonitor)
 {
-  return pMonitor->pDriver->pGetHeight(pMonitor);
+  return MONITOR_Driver->pGetHeight(pMonitor);
 }
 
 /***********************************************************************
@@ -51,9 +78,42 @@
  */
 int MONITOR_GetDepth(MONITOR *pMonitor)
 {
-  return pMonitor->pDriver->pGetDepth(pMonitor);
+  return MONITOR_Driver->pGetDepth(pMonitor);
 }
 
+/***********************************************************************
+ *              MONITOR_GetScreenSaveActive
+ */
+BOOL MONITOR_GetScreenSaveActive(MONITOR *pMonitor)
+{
+  return MONITOR_Driver->pGetScreenSaveActive(pMonitor);
+}
+
+/***********************************************************************
+ *              MONITOR_SetScreenSaveActive
+ */
+void MONITOR_SetScreenSaveActive(MONITOR *pMonitor, BOOL bActivate)
+{
+  MONITOR_Driver->pSetScreenSaveActive(pMonitor, bActivate);
+}
+
+/***********************************************************************
+ *              MONITOR_GetScreenSaveTimeout
+ */
+int MONITOR_GetScreenSaveTimeout(MONITOR *pMonitor)
+{
+  return MONITOR_Driver->pGetScreenSaveTimeout(pMonitor);
+}
+
+/***********************************************************************
+ *              MONITOR_SetScreenSaveTimeout
+ */
+void MONITOR_SetScreenSaveTimeout(MONITOR *pMonitor, int nTimeout)
+{
+  MONITOR_Driver->pSetScreenSaveTimeout(pMonitor, nTimeout);
+}
+
+
 /**********************************************************************/
 
 HMONITOR WINAPI MonitorFromPoint(POINT ptScreenCoords, DWORD dwFlags)
diff --git a/windows/scroll.c b/windows/scroll.c
index ddf6d7c..97523b0 100644
--- a/windows/scroll.c
+++ b/windows/scroll.c
@@ -8,6 +8,7 @@
  */
 
 #include <stdlib.h>
+
 #include "winuser.h"
 #include "class.h"
 #include "dc.h"
diff --git a/windows/ttydrv/init.c b/windows/ttydrv/init.c
index b7e6396..7f6a15b 100644
--- a/windows/ttydrv/init.c
+++ b/windows/ttydrv/init.c
@@ -6,12 +6,22 @@
 
 #include "clipboard.h"
 #include "desktop.h"
-#include "display.h"
 #include "keyboard.h"
 #include "message.h"
 #include "monitor.h"
+#include "mouse.h"
+#include "user.h"
+#include "win.h"
 #include "ttydrv.h"
 
+USER_DRIVER TTYDRV_USER_Driver =
+{
+  TTYDRV_USER_Initialize,
+  TTYDRV_USER_Finalize,
+  TTYDRV_USER_BeginDebugging,
+  TTYDRV_USER_EndDebugging
+};
+
 CLIPBOARD_DRIVER TTYDRV_CLIPBOARD_Driver =
 {
   TTYDRV_CLIPBOARD_EmptyClipboard,
@@ -47,22 +57,31 @@
   TTYDRV_KEYBOARD_VkKeyScan,
   TTYDRV_KEYBOARD_MapVirtualKey,
   TTYDRV_KEYBOARD_GetKeyNameText,
-  TTYDRV_KEYBOARD_ToAscii
+  TTYDRV_KEYBOARD_ToAscii,
+  TTYDRV_KEYBOARD_GetBeepActive,
+  TTYDRV_KEYBOARD_SetBeepActive,
+  TTYDRV_KEYBOARD_Beep
 };
 
 MONITOR_DRIVER TTYDRV_MONITOR_Driver =
 {
   TTYDRV_MONITOR_Initialize,
   TTYDRV_MONITOR_Finalize,
+  TTYDRV_MONITOR_IsSingleWindow,
   TTYDRV_MONITOR_GetWidth,
   TTYDRV_MONITOR_GetHeight,
-  TTYDRV_MONITOR_GetDepth
+  TTYDRV_MONITOR_GetDepth,
+  TTYDRV_MONITOR_GetScreenSaveActive,
+  TTYDRV_MONITOR_SetScreenSaveActive,
+  TTYDRV_MONITOR_GetScreenSaveTimeout,
+  TTYDRV_MONITOR_SetScreenSaveTimeout
 };
 
 MOUSE_DRIVER TTYDRV_MOUSE_Driver =
 {
   TTYDRV_MOUSE_SetCursor,
-  TTYDRV_MOUSE_MoveCursor
+  TTYDRV_MOUSE_MoveCursor,
+  TTYDRV_MOUSE_EnableWarpPointer
 };
 
 WND_DRIVER TTYDRV_WND_Driver =
diff --git a/windows/ttydrv/keyboard.c b/windows/ttydrv/keyboard.c
index a6a1f6f..8010b79 100644
--- a/windows/ttydrv/keyboard.c
+++ b/windows/ttydrv/keyboard.c
@@ -53,6 +53,27 @@
   return 0;
 }
 
+/***********************************************************************
+ *		TTYDRV_KEYBOARD_GetBeepActive
+ */
+BOOL TTYDRV_KEYBOARD_GetBeepActive()
+{
+  return FALSE;
+}
+
+/***********************************************************************
+ *		TTYDRV_KEYBOARD_SetBeepActive
+ */
+void TTYDRV_KEYBOARD_SetBeepActive(BOOL bActivate)
+{
+}
+
+/***********************************************************************
+ *		TTYDRV_KEYBOARD_Beep
+ */
+void TTYDRV_KEYBOARD_Beep()
+{
+}
 
 
 
diff --git a/windows/ttydrv/main.c b/windows/ttydrv/main.c
index 88e39b8..b398585 100644
--- a/windows/ttydrv/main.c
+++ b/windows/ttydrv/main.c
@@ -5,46 +5,50 @@
  *
  */
 
+#include "clipboard.h"
+#include "desktop.h"
+#include "message.h"
+#include "keyboard.h"
+#include "monitor.h"
+#include "mouse.h"
 #include "ttydrv.h"
+#include "win.h"
 
 /***********************************************************************
- *              TTYDRV_MAIN_Initialize
+ *              TTYDRV_USER_Initialize
  */
-void TTYDRV_MAIN_Initialize()
+BOOL TTYDRV_USER_Initialize(void)
 {
+  CLIPBOARD_Driver = &TTYDRV_CLIPBOARD_Driver;
+  DESKTOP_Driver = &TTYDRV_DESKTOP_Driver;
+  EVENT_Driver = &TTYDRV_EVENT_Driver;
+  KEYBOARD_Driver = &TTYDRV_KEYBOARD_Driver;
+  MONITOR_Driver = &TTYDRV_MONITOR_Driver;
+  MOUSE_Driver = &TTYDRV_MOUSE_Driver;
+  WND_Driver = &TTYDRV_WND_Driver;
+
+  return TRUE;
 }
 
 /***********************************************************************
- *              TTYDRV_MAIN_Finalize
+ *              TTYDRV_USER_Finalize
  */
-void TTYDRV_MAIN_Finalize()
+void TTYDRV_USER_Finalize(void)
 {
 }
 
-/***********************************************************************
- *              TTYDRV_MAIN_ParseOptions
+/**************************************************************************
+ *		TTYDRV_USER_BeginDebugging
  */
-void TTYDRV_MAIN_ParseOptions(int *argc, char *argv[])
+void TTYDRV_USER_BeginDebugging(void)
 {
 }
 
-/***********************************************************************
- *		TTYDRV_MAIN_Create
+/**************************************************************************
+ *		TTYDRV_USER_EndDebugging
  */
-void TTYDRV_MAIN_Create()
+void TTYDRV_USER_EndDebugging(void)
 {
 }
 
-/***********************************************************************
- *           TTYDRV_MAIN_SaveSetup
- */
-void TTYDRV_MAIN_SaveSetup()
-{
-}
 
-/***********************************************************************
- *           TTYDRV_MAIN_RestoreSetup
- */
-void TTYDRV_MAIN_RestoreSetup()
-{
-}
diff --git a/windows/ttydrv/monitor.c b/windows/ttydrv/monitor.c
index 469330a..bf5297c 100644
--- a/windows/ttydrv/monitor.c
+++ b/windows/ttydrv/monitor.c
@@ -34,6 +34,14 @@
 }
 
 /***********************************************************************
+ *              TTYDRV_MONITOR_IsSingleWindow
+ */
+BOOL TTYDRV_MONITOR_IsSingleWindow(MONITOR *pMonitor)
+{
+  return TRUE;
+}
+
+/***********************************************************************
  *              TTYDRV_MONITOR_GetWidth
  *
  * Return the width of the monitor
@@ -71,3 +79,42 @@
 
   return pTTYMonitor->depth;
 }
+
+/***********************************************************************
+ *              TTYDRV_MONITOR_GetScreenSaveActive
+ *
+ * Returns the active status of the screen saver
+ */
+BOOL TTYDRV_MONITOR_GetScreenSaveActive(MONITOR *pMonitor)
+{
+  return FALSE;
+}
+
+/***********************************************************************
+ *              TTYDRV_MONITOR_SetScreenSaveActive
+ *
+ * Activate/Deactivate the screen saver
+ */
+void TTYDRV_MONITOR_SetScreenSaveActive(MONITOR *pMonitor, BOOL bActivate)
+{
+}
+
+/***********************************************************************
+ *              TTYDRV_MONITOR_GetScreenSaveTimeout
+ *
+ * Return the screen saver timeout
+ */
+int TTYDRV_MONITOR_GetScreenSaveTimeout(MONITOR *pMonitor)
+{
+  return 0;
+}
+
+/***********************************************************************
+ *              TTYDRV_MONITOR_SetScreenSaveTimeout
+ *
+ * Set the screen saver timeout
+ */
+void TTYDRV_MONITOR_SetScreenSaveTimeout(
+  MONITOR *pMonitor, int nTimeout)
+{
+}
diff --git a/windows/ttydrv/mouse.c b/windows/ttydrv/mouse.c
index fba316d..9ea016e 100644
--- a/windows/ttydrv/mouse.c
+++ b/windows/ttydrv/mouse.c
@@ -19,3 +19,11 @@
 void TTYDRV_MOUSE_MoveCursor(WORD wAbsX, WORD wAbsY)
 {
 }
+
+/***********************************************************************
+ *           TTYDRV_MOUSE_EnableWarpPointer
+ */
+BOOL TTYDRV_MOUSE_EnableWarpPointer(BOOL bEnable)
+{
+  return TRUE;
+}
diff --git a/windows/ttydrv/wnd.c b/windows/ttydrv/wnd.c
index 7085ac9..e488037 100644
--- a/windows/ttydrv/wnd.c
+++ b/windows/ttydrv/wnd.c
@@ -48,7 +48,7 @@
 }
 
 /*****************************************************************
- *		X11DRV_WND_SetParent
+ *		TTYDRV_WND_SetParent
  */
 WND *TTYDRV_WND_SetParent(WND *wndPtr, WND *pWndParent)
 {
@@ -64,8 +64,6 @@
 
 /***********************************************************************
  *           WINPOS_SetXWindowPos
- *
- * SetWindowPos() for an X window. Used by the real SetWindowPos().
  */
 void TTYDRV_WND_SetWindowPos(WND *wndPtr, const WINDOWPOS *winpos, BOOL bSMC_SETXPOS)
 {
@@ -131,4 +129,3 @@
 {
   return FALSE;
 }
-
diff --git a/windows/win.c b/windows/win.c
index e2ea887..402319d 100644
--- a/windows/win.c
+++ b/windows/win.c
@@ -4,8 +4,6 @@
  * Copyright 1993, 1994 Alexandre Julliard
  */
 
-#include "config.h"
-
 #include <stdlib.h>
 #include <string.h>
 #include "wine/winbase16.h"
@@ -36,13 +34,9 @@
 #include "local.h"
 #include "desktop.h"
 
-#ifndef X_DISPLAY_MISSING
-extern DESKTOP_DRIVER X11DRV_DESKTOP_Driver;
-extern WND_DRIVER X11DRV_WND_Driver;
-#else /* X_DISPLAY_MISSING */
-extern DESKTOP_DRIVER TTYDRV_DESKTOP_Driver;
-extern WND_DRIVER TTYDRV_WND_Driver;
-#endif /* X_DISPLAY_MISSING */
+/**********************************************************************/
+
+WND_DRIVER *WND_Driver = NULL;
 
 /* Desktop window */
 static WND *pWndDesktop = NULL;
@@ -624,13 +618,8 @@
     pWndDesktop = (WND *) USER_HEAP_LIN_ADDR( hwndDesktop );
 
     pDesktop = (DESKTOP *) pWndDesktop->wExtra;
-#ifndef X_DISPLAY_MISSING
-    pDesktop->pDriver = &X11DRV_DESKTOP_Driver;
-    pWndDesktop->pDriver = &X11DRV_WND_Driver;
-#else /* X_DISPLAY_MISSING */
-    pDesktop->pDriver = &TTYDRV_DESKTOP_Driver;
-    pWndDesktop->pDriver = &TTYDRV_WND_Driver;
-#endif /* X_DISPLAY_MISSING */
+    pDesktop->pDriver = DESKTOP_Driver;
+    pWndDesktop->pDriver = WND_Driver;
 
     pDesktop->pDriver->pInitialize(pDesktop);
     pWndDesktop->pDriver->pInitialize(pWndDesktop);
@@ -1179,7 +1168,7 @@
     WIN_CheckFocus(pWnd);
 
     if( CARET_GetHwnd() == pWnd->hwndSelf ) DestroyCaret();
-    CLIPBOARD_GetDriver()->pResetOwner( pWnd, TRUE ); 
+    CLIPBOARD_Driver->pResetOwner( pWnd, TRUE ); 
 
     /*
      * Send the WM_DESTROY to the window.
@@ -1320,7 +1309,7 @@
             }
 	}
 
-    CLIPBOARD_GetDriver()->pResetOwner( wndPtr, FALSE ); /* before the window is unmapped */
+    CLIPBOARD_Driver->pResetOwner( wndPtr, FALSE ); /* before the window is unmapped */
 
       /* Hide the window */
 
diff --git a/windows/winpos.c b/windows/winpos.c
index 99399c0..aadcd07 100644
--- a/windows/winpos.c
+++ b/windows/winpos.c
@@ -5,8 +5,6 @@
  *                       1995, 1996, 1999 Alex Korobka
  */
 
-#include "x11drv.h"
-
 #include <string.h>
 #include "sysmetrics.h"
 #include "heap.h"
diff --git a/windows/x11drv/event.c b/windows/x11drv/event.c
index e1bf6da..106903a 100644
--- a/windows/x11drv/event.c
+++ b/windows/x11drv/event.c
@@ -1156,7 +1156,10 @@
   unsigned char*	p_data = NULL;
   union {
     Atom		atom_aux;
-    POINT	pt_aux;
+    struct {
+      int x;
+      int y;
+    } pt_aux;
     int		i;
   }		u;
   int			x, y;
@@ -1278,7 +1281,6 @@
   int		x, y, drop32 = FALSE ;
   union {
     Atom	atom_aux;
-    POINT	pt_aux;
     int         i;
     Window      w_aux;
   }		u; /* unused */
@@ -1456,7 +1458,7 @@
 {
   if( !Options.managed && X11DRV_GetXRootWindow() == DefaultRootWindow(display) &&
       (COLOR_GetSystemPaletteFlags() & COLOR_PRIVATE) && GetFocus() )
-    TSXInstallColormap( display, X11DRV_COLOR_GetColormap() );
+    TSXInstallColormap( display, X11DRV_PALETTE_GetColormap() );
 }
 #endif
 
diff --git a/windows/x11drv/init.c b/windows/x11drv/init.c
index ead5570..d7a59e1 100644
--- a/windows/x11drv/init.c
+++ b/windows/x11drv/init.c
@@ -10,13 +10,22 @@
 
 #include "clipboard.h"
 #include "desktop.h"
-#include "display.h"
 #include "keyboard.h"
 #include "message.h"
 #include "monitor.h"
+#include "mouse.h"
+#include "user.h"
 #include "win.h"
 #include "x11drv.h"
 
+USER_DRIVER X11DRV_USER_Driver =
+{
+  X11DRV_USER_Initialize,
+  X11DRV_USER_Finalize,
+  X11DRV_USER_BeginDebugging,
+  X11DRV_USER_EndDebugging
+};
+
 CLIPBOARD_DRIVER X11DRV_CLIPBOARD_Driver =
 {
   X11DRV_CLIPBOARD_EmptyClipboard,
@@ -52,22 +61,31 @@
   X11DRV_KEYBOARD_VkKeyScan,
   X11DRV_KEYBOARD_MapVirtualKey,
   X11DRV_KEYBOARD_GetKeyNameText,
-  X11DRV_KEYBOARD_ToAscii
+  X11DRV_KEYBOARD_ToAscii,
+  X11DRV_KEYBOARD_GetBeepActive,
+  X11DRV_KEYBOARD_SetBeepActive,
+  X11DRV_KEYBOARD_Beep
 };
 
 MONITOR_DRIVER X11DRV_MONITOR_Driver =
 {
   X11DRV_MONITOR_Initialize,
   X11DRV_MONITOR_Finalize,
+  X11DRV_MONITOR_IsSingleWindow,
   X11DRV_MONITOR_GetWidth,
   X11DRV_MONITOR_GetHeight,
-  X11DRV_MONITOR_GetDepth
+  X11DRV_MONITOR_GetDepth,
+  X11DRV_MONITOR_GetScreenSaveActive,
+  X11DRV_MONITOR_SetScreenSaveActive,
+  X11DRV_MONITOR_GetScreenSaveTimeout,
+  X11DRV_MONITOR_SetScreenSaveTimeout
 };
 
 MOUSE_DRIVER X11DRV_MOUSE_Driver =
 {
   X11DRV_MOUSE_SetCursor,
-  X11DRV_MOUSE_MoveCursor
+  X11DRV_MOUSE_MoveCursor,
+  X11DRV_MOUSE_EnableWarpPointer
 };
 
 WND_DRIVER X11DRV_WND_Driver =
diff --git a/windows/x11drv/keyboard.c b/windows/x11drv/keyboard.c
index baabca7..3f011ed 100644
--- a/windows/x11drv/keyboard.c
+++ b/windows/x11drv/keyboard.c
@@ -1144,6 +1144,40 @@
     return ret;
 }
 
-#endif /* !defined(X_DISPLAY_MISSING) */
+/***********************************************************************
+ *		X11DRV_KEYBOARD_GetBeepActive
+ */
+BOOL X11DRV_KEYBOARD_GetBeepActive()
+{
+  XKeyboardState  keyboard_state;
 
+  TSXGetKeyboardControl(display, &keyboard_state);
+
+  return keyboard_state.bell_percent != 0;
+}
+
+/***********************************************************************
+ *		X11DRV_KEYBOARD_SetBeepActive
+ */
+void X11DRV_KEYBOARD_SetBeepActive(BOOL bActivate)
+{
+  XKeyboardControl keyboard_value;
+  
+  if(bActivate)
+    keyboard_value.bell_percent = -1;
+  else
+    keyboard_value.bell_percent = 0;
+  
+  TSXChangeKeyboardControl(display, KBBellPercent, &keyboard_value);
+}
+
+/***********************************************************************
+ *		X11DRV_KEYBOARD_Beep
+ */
+void X11DRV_KEYBOARD_Beep()
+{
+  TSXBell(display, 0);
+}
+
+#endif /* !defined(X_DISPLAY_MISSING) */
 
diff --git a/windows/x11drv/main.c b/windows/x11drv/main.c
index 9d2a74e..d5cc1fa 100644
--- a/windows/x11drv/main.c
+++ b/windows/x11drv/main.c
@@ -18,17 +18,30 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+
+#include "clipboard.h"
 #include "console.h"
 #include "debug.h"
 #include "desktop.h"
+#include "keyboard.h"
 #include "main.h"
+#include "message.h"
 #include "monitor.h"
+#include "mouse.h"
 #include "options.h"
 #include "win.h"
 #include "windef.h"
 #include "x11drv.h"
 #include "xmalloc.h"
 #include "version.h"
+#include "win.h"
+
+/**********************************************************************/
+
+void X11DRV_USER_ParseOptions(int *argc, char *argv[]);
+void X11DRV_USER_Create(void);
+void X11DRV_USER_SaveSetup(void);
+void X11DRV_USER_RestoreSetup(void);
 
 /**********************************************************************/
 
@@ -89,10 +102,18 @@
 }
 
 /***********************************************************************
- *              X11DRV_MAIN_Initialize
+ *              X11DRV_USER_Initialize
  */
-void X11DRV_MAIN_Initialize()
+BOOL X11DRV_USER_Initialize(void)
 {
+  CLIPBOARD_Driver = &X11DRV_CLIPBOARD_Driver;
+  DESKTOP_Driver = &X11DRV_DESKTOP_Driver;
+  EVENT_Driver = &X11DRV_EVENT_Driver;
+  KEYBOARD_Driver = &X11DRV_KEYBOARD_Driver;
+  MONITOR_Driver = &X11DRV_MONITOR_Driver;
+  MOUSE_Driver = &X11DRV_MOUSE_Driver;
+  WND_Driver = &X11DRV_WND_Driver;
+
   /* We need this before calling any Xlib function */
   InitializeCriticalSection( &X11DRV_CritSection );
   MakeCriticalSectionGlobal( &X11DRV_CritSection );
@@ -100,22 +121,43 @@
   TSXrmInitialize();
   
   putenv("XKB_DISABLE="); /* Disable XKB extension if present. */
+
+  X11DRV_USER_ParseOptions( Options.argc, Options.argv );
+  X11DRV_USER_Create();
+  X11DRV_USER_SaveSetup();
 }
 
 /***********************************************************************
- *              X11DRV_MAIN_Finalize
+ *              X11DRV_USER_Finalize
  */
-void X11DRV_MAIN_Finalize()
+void X11DRV_USER_Finalize(void)
+{
+  X11DRV_USER_RestoreSetup();
+}
+
+/**************************************************************************
+ *		X11DRV_USER_BeginDebugging
+ */
+void X11DRV_USER_BeginDebugging(void)
+{
+  TSXUngrabServer(display);
+  TSXFlush(display);
+}
+
+/**************************************************************************
+ *		X11DRV_USER_EndDebugging
+ */
+void X11DRV_USER_EndDebugging(void)
 {
 }
 
 /***********************************************************************
- *		 X11DRV_MAIN_GetResource
+ *		 X11DRV_USER_GetResource
  *
  * Fetch the value of resource 'name' using the correct instance name.
  * 'name' must begin with '.' or '*'
  */
-static int X11DRV_MAIN_GetResource( XrmDatabase db, char *name, XrmValue *value )
+static int X11DRV_USER_GetResource( XrmDatabase db, char *name, XrmValue *value )
 {
   char *buff_instance, *buff_class;
   char *dummy;
@@ -135,10 +177,10 @@
 }
 
 /***********************************************************************
- *              X11DRV_MAIN_ParseOptions
+ *              X11DRV_USER_ParseOptions
  * Parse command line options and open display.
  */
-void X11DRV_MAIN_ParseOptions(int *argc, char *argv[])
+void X11DRV_USER_ParseOptions(int *argc, char *argv[])
 {
   int i;
   char *display_name = NULL;
@@ -155,7 +197,7 @@
   /* Open display */
   
   if (display_name == NULL &&
-      X11DRV_MAIN_GetResource( db, ".display", &value )) display_name = value.addr;
+      X11DRV_USER_GetResource( db, ".display", &value )) display_name = value.addr;
   
   if (!(display = TSXOpenDisplay( display_name )))
     {
@@ -184,35 +226,35 @@
 		     Options.programName, argc, argv );
   
   /* Get all options */
-  if (X11DRV_MAIN_GetResource( db, ".iconic", &value ))
+  if (X11DRV_USER_GetResource( db, ".iconic", &value ))
     Options.cmdShow = SW_SHOWMINIMIZED;
-  if (X11DRV_MAIN_GetResource( db, ".privatemap", &value ))
+  if (X11DRV_USER_GetResource( db, ".privatemap", &value ))
     Options.usePrivateMap = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".fixedmap", &value ))
+  if (X11DRV_USER_GetResource( db, ".fixedmap", &value ))
     Options.useFixedMap = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".synchronous", &value ))
+  if (X11DRV_USER_GetResource( db, ".synchronous", &value ))
     Options.synchronous = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".backingstore", &value ))
+  if (X11DRV_USER_GetResource( db, ".backingstore", &value ))
     Options.backingstore = TRUE;	
-  if (X11DRV_MAIN_GetResource( db, ".debug", &value ))
+  if (X11DRV_USER_GetResource( db, ".debug", &value ))
     Options.debug = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".failreadonly", &value ))
+  if (X11DRV_USER_GetResource( db, ".failreadonly", &value ))
     Options.failReadOnly = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".perfect", &value ))
+  if (X11DRV_USER_GetResource( db, ".perfect", &value ))
     Options.perfectGraphics = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".depth", &value))
+  if (X11DRV_USER_GetResource( db, ".depth", &value))
     Options.screenDepth = atoi( value.addr );
-  if (X11DRV_MAIN_GetResource( db, ".desktop", &value))
+  if (X11DRV_USER_GetResource( db, ".desktop", &value))
     Options.desktopGeometry = value.addr;
-  if (X11DRV_MAIN_GetResource( db, ".language", &value))
+  if (X11DRV_USER_GetResource( db, ".language", &value))
     MAIN_ParseLanguageOption( (char *)value.addr );
-  if (X11DRV_MAIN_GetResource( db, ".managed", &value))
+  if (X11DRV_USER_GetResource( db, ".managed", &value))
     Options.managed = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".mode", &value))
+  if (X11DRV_USER_GetResource( db, ".mode", &value))
     MAIN_ParseModeOption( (char *)value.addr );
-  if (X11DRV_MAIN_GetResource( db, ".debugoptions", &value))
+  if (X11DRV_USER_GetResource( db, ".debugoptions", &value))
     MAIN_ParseDebugOptions((char*)value.addr);
-  if (X11DRV_MAIN_GetResource( db, ".debugmsg", &value))
+  if (X11DRV_USER_GetResource( db, ".debugmsg", &value))
     {
 #ifndef DEBUG_RUNTIME
       MSG("%s: Option \"-debugmsg\" not implemented.\n" \
@@ -224,7 +266,7 @@
 #endif
     }
   
-  if (X11DRV_MAIN_GetResource( db, ".dll", &value))
+  if (X11DRV_USER_GetResource( db, ".dll", &value))
   {
       if (Options.dllFlags)
       {
@@ -236,35 +278,35 @@
       else Options.dllFlags = xstrdup((char *)value.addr);
   }
   
-  if (X11DRV_MAIN_GetResource( db, ".winver", &value))
+  if (X11DRV_USER_GetResource( db, ".winver", &value))
     VERSION_ParseWinVersion( (char*)value.addr );
-  if (X11DRV_MAIN_GetResource( db, ".dosver", &value))
+  if (X11DRV_USER_GetResource( db, ".dosver", &value))
     VERSION_ParseDosVersion( (char*)value.addr );
-  if (X11DRV_MAIN_GetResource( db, ".config", &value))
+  if (X11DRV_USER_GetResource( db, ".config", &value))
     Options.configFileName = xstrdup((char *)value.addr);
-  if (X11DRV_MAIN_GetResource( db, ".nodga", &value))
+  if (X11DRV_USER_GetResource( db, ".nodga", &value))
     Options.noDGA = TRUE;
-  if (X11DRV_MAIN_GetResource( db, ".console", &value))
+  if (X11DRV_USER_GetResource( db, ".console", &value))
       driver.driver_list = xstrdup((char *)value.addr);
   else
       driver.driver_list = CONSOLE_DEFAULT_DRIVER;
 }
 
 /***********************************************************************
- *		X11DRV_MAIN_ErrorHandler
+ *		X11DRV_USER_ErrorHandler
  */
-static int X11DRV_MAIN_ErrorHandler(Display *display, XErrorEvent *error_evt)
+static int X11DRV_USER_ErrorHandler(Display *display, XErrorEvent *error_evt)
 {
     kill( getpid(), SIGHUP ); /* force an entry in the debugger */
     return 0;
 }
 
 /***********************************************************************
- *		X11DRV_MAIN_Create
+ *		X11DRV_USER_Create
  */
-void X11DRV_MAIN_Create()
+void X11DRV_USER_Create()
 {
-  if (Options.synchronous) XSetErrorHandler( X11DRV_MAIN_ErrorHandler );
+  if (Options.synchronous) XSetErrorHandler( X11DRV_USER_ErrorHandler );
   
   if (Options.desktopGeometry && Options.managed)
     {
@@ -279,17 +321,17 @@
 }
 
 /***********************************************************************
- *           X11DRV_MAIN_SaveSetup
+ *           X11DRV_USER_SaveSetup
  */
-void X11DRV_MAIN_SaveSetup()
+void X11DRV_USER_SaveSetup()
 {
   TSXGetKeyboardControl(display, &X11DRV_XKeyboardState);
 }
 
 /***********************************************************************
- *           X11DRV_MAIN_RestoreSetup
+ *           X11DRV_USER_RestoreSetup
  */
-void X11DRV_MAIN_RestoreSetup()
+void X11DRV_USER_RestoreSetup()
 {
   XKeyboardControl keyboard_value;
   
diff --git a/windows/x11drv/monitor.c b/windows/x11drv/monitor.c
index 97e3080..debec81 100644
--- a/windows/x11drv/monitor.c
+++ b/windows/x11drv/monitor.c
@@ -184,6 +184,17 @@
 }
 
 /***********************************************************************
+ *              X11DRV_MONITOR_IsSingleWindow
+ */
+BOOL X11DRV_MONITOR_IsSingleWindow(MONITOR *pMonitor)
+{
+  X11DRV_MONITOR_DATA *pX11Monitor =
+    (X11DRV_MONITOR_DATA *) pMonitor->pDriverData;
+
+  return (pX11Monitor->rootWindow != DefaultRootWindow(display));
+}
+
+/***********************************************************************
  *              X11DRV_MONITOR_GetWidth
  *
  * Return the width of the monitor
@@ -222,6 +233,53 @@
   return pX11Monitor->depth;
 }
 
+/***********************************************************************
+ *              X11DRV_MONITOR_GetScreenSaveActive
+ *
+ * Returns the active status of the screen saver
+ */
+BOOL X11DRV_MONITOR_GetScreenSaveActive(MONITOR *pMonitor)
+{
+  int timeout, temp;
+  TSXGetScreenSaver(display, &timeout, &temp, &temp, &temp);
+  return timeout!=NULL;
+}
+
+/***********************************************************************
+ *              X11DRV_MONITOR_SetScreenSaveActive
+ *
+ * Activate/Deactivate the screen saver
+ */
+void X11DRV_MONITOR_SetScreenSaveActive(MONITOR *pMonitor, BOOL bActivate)
+{
+  if(bActivate)
+    TSXActivateScreenSaver(display);
+  else
+    TSXResetScreenSaver(display);
+}
+
+/***********************************************************************
+ *              X11DRV_MONITOR_GetScreenSaveTimeout
+ *
+ * Return the screen saver timeout
+ */
+int X11DRV_MONITOR_GetScreenSaveTimeout(MONITOR *pMonitor)
+{
+  int timeout, temp;
+  TSXGetScreenSaver(display, &timeout, &temp, &temp, &temp);
+  return timeout;
+}
+
+/***********************************************************************
+ *              X11DRV_MONITOR_SetScreenSaveTimeout
+ *
+ * Set the screen saver timeout
+ */
+void X11DRV_MONITOR_SetScreenSaveTimeout(
+  MONITOR *pMonitor, int nTimeout)
+{
+  TSXSetScreenSaver(display, nTimeout, 60, 
+		    DefaultBlanking, DefaultExposures);
+}
+
 #endif /* X_DISPLAY_MISSING */
-
-
diff --git a/windows/x11drv/mouse.c b/windows/x11drv/mouse.c
index 7eb8f7f..19eaac2 100644
--- a/windows/x11drv/mouse.c
+++ b/windows/x11drv/mouse.c
@@ -12,7 +12,7 @@
 
 #include "callback.h"
 #include "debug.h"
-#include "display.h"
+#include "mouse.h"
 #include "win.h"
 #include "windef.h"
 #include "x11drv.h"
@@ -21,7 +21,7 @@
 
 Cursor X11DRV_MOUSE_XCursor = None;    /* Current X cursor */
 
-BOOL X11DRV_MOUSE_DisableWarpPointer = FALSE;  /* hack; see DISPLAY_MoveCursor */
+static BOOL X11DRV_MOUSE_WarpPointer = FALSE;  /* hack; see DISPLAY_MoveCursor */
 
 /***********************************************************************
  *		X11DRV_MOUSE_DoSetCursor
@@ -203,7 +203,7 @@
   int rootX, rootY, winX, winY;
   unsigned int xstate;
   
-  if (X11DRV_MOUSE_DisableWarpPointer) return;
+  if (!X11DRV_MOUSE_WarpPointer) return;
 
   if (!TSXQueryPointer( display, X11DRV_GetXRootWindow(), &root, &child,
 			&rootX, &rootY, &winX, &winY, &xstate ))
@@ -218,4 +218,16 @@
 		  0, 0, 0, 0, wAbsX, wAbsY );
 }
 
+/***********************************************************************
+ *           X11DRV_MOUSE_EnableWarpPointer
+ */
+BOOL X11DRV_MOUSE_EnableWarpPointer(BOOL bEnable)
+{
+  BOOL bOldEnable = X11DRV_MOUSE_WarpPointer;
+
+  X11DRV_MOUSE_WarpPointer = bEnable;
+
+  return bOldEnable;
+}
+
 #endif /* !defined(X_DISPLAY_MISSING) */
diff --git a/windows/x11drv/wnd.c b/windows/x11drv/wnd.c
index cb5f474..a877dec 100644
--- a/windows/x11drv/wnd.c
+++ b/windows/x11drv/wnd.c
@@ -196,7 +196,7 @@
       wndPtr->flags |= WIN_NATIVE;
 
       win_attr.bit_gravity   = BGNorthWest;
-      win_attr.colormap      = X11DRV_COLOR_GetColormap();
+      win_attr.colormap      = X11DRV_PALETTE_PaletteXColormap;
       win_attr.backing_store = Options.backingstore ? WhenMapped : NotUseful;
       win_attr.save_under    = ((classPtr->style & CS_SAVEBITS) != 0);
       win_attr.cursor        = X11DRV_MOUSE_XCursor;
@@ -548,8 +548,8 @@
   
   if (!hwnd)	/* If setting the focus to 0, uninstall the colormap */
     {
-      if (COLOR_GetSystemPaletteFlags() & COLOR_PRIVATE)
-	TSXUninstallColormap( display, X11DRV_COLOR_GetColormap() );
+      if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
+	TSXUninstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
       return;
     }
   
@@ -561,8 +561,8 @@
     return;  /* If window is not viewable, don't change anything */
   
   TSXSetInputFocus( display, win, RevertToParent, CurrentTime );
-  if (COLOR_GetSystemPaletteFlags() & COLOR_PRIVATE)
-    TSXInstallColormap( display, X11DRV_COLOR_GetColormap() );
+  if (X11DRV_PALETTE_PaletteFlags & X11DRV_PALETTE_PRIVATE)
+    TSXInstallColormap( display, X11DRV_PALETTE_PaletteXColormap );
   
   EVENT_Synchronize();
 }
@@ -716,10 +716,7 @@
  */
 BOOL X11DRV_WND_IsSelfClipping(WND *wndPtr)
 {
-  if( X11DRV_WND_GetXWindow(wndPtr) ) 
-      return TRUE; /* X itself will do the clipping */
-
-  return FALSE;
+  return X11DRV_WND_GetXWindow(wndPtr) != None;
 }
 
 #endif /* !defined(X_DISPLAY_MISSING) */